package shop.alien.store.util;

/**
 * 正整数的 Base62 编解码（0-9A-Za-z），用于短链码生成。
 */
public final class Base62Util {

    private static final String ALPHABET = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
    private static final int BASE = ALPHABET.length();

    private Base62Util() {
    }

    /**
     * 将正整数编码为 Base62 字符串（不含符号位，{@code value == 0} 时结果为单个首字符）。
     */
    public static String encodePositiveLong(long value) {
        if (value < 0) {
            throw new IllegalArgumentException("value must be non-negative");
        }
        if (value == 0) {
            return String.valueOf(ALPHABET.charAt(0));
        }
        StringBuilder sb = new StringBuilder();
        long v = value;
        while (v > 0) {
            sb.append(ALPHABET.charAt((int) (v % BASE)));
            v /= BASE;
        }
        return sb.reverse().toString();
    }

    /**
     * Base62 解码为 long；非法字符时抛出 {@link IllegalArgumentException}。
     */
    public static long decodeToPositiveLong(String code) {
        if (code == null || code.isEmpty()) {
            throw new IllegalArgumentException("code is empty");
        }
        long result = 0;
        for (int i = 0; i < code.length(); i++) {
            int digit = ALPHABET.indexOf(code.charAt(i));
            if (digit < 0) {
                throw new IllegalArgumentException("invalid base62 char: " + code.charAt(i));
            }
            result = result * BASE + digit;
            if (result < 0) {
                throw new IllegalArgumentException("overflow");
            }
        }
        return result;
    }
}
