package com.xfestudio.xfeservermanager.core.economy;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Objects;

/** Exact conversion between API decimal strings and SQLite integer minor units. */
public final class EconomyAmounts {
    public static final int MAX_FRACTION_DIGITS = 6;
    public static final long MAX_ABSOLUTE_MINOR_UNITS = 9_000_000_000_000_000L;

    private EconomyAmounts() { }

    public static long parse(String value, int fractionDigits, String field) {
        validateFractionDigits(fractionDigits);
        String raw = Objects.toString(value, "").strip();
        if (raw.isEmpty() || raw.length() > 64) {
            throw new IllegalArgumentException(field + " must be a decimal number");
        }
        try {
            BigDecimal decimal = new BigDecimal(raw).setScale(fractionDigits, RoundingMode.UNNECESSARY);
            long minor = decimal.movePointRight(fractionDigits).longValueExact();
            if (minor < -MAX_ABSOLUTE_MINOR_UNITS || minor > MAX_ABSOLUTE_MINOR_UNITS) {
                throw new IllegalArgumentException(field + " is outside the supported range");
            }
            return minor;
        } catch (ArithmeticException | NumberFormatException invalid) {
            throw new IllegalArgumentException(field + " has more than " + fractionDigits
                    + " decimal places or is outside the supported range", invalid);
        }
    }

    public static long parsePositive(String value, int fractionDigits, String field) {
        long amount = parse(value, fractionDigits, field);
        if (amount <= 0) throw new IllegalArgumentException(field + " must be greater than zero");
        return amount;
    }

    public static String format(long minorUnits, int fractionDigits) {
        validateFractionDigits(fractionDigits);
        return BigDecimal.valueOf(minorUnits, fractionDigits).setScale(fractionDigits).toPlainString();
    }

    public static String normalize(String value, int fractionDigits, String field) {
        return format(parse(value, fractionDigits, field), fractionDigits);
    }

    public static long add(long left, long right, String field) {
        try {
            long result = Math.addExact(left, right);
            if (result < -MAX_ABSOLUTE_MINOR_UNITS || result > MAX_ABSOLUTE_MINOR_UNITS) {
                throw new ArithmeticException("range");
            }
            return result;
        } catch (ArithmeticException overflow) {
            throw new IllegalArgumentException(field + " is outside the supported range", overflow);
        }
    }

    private static void validateFractionDigits(int fractionDigits) {
        if (fractionDigits < 0 || fractionDigits > MAX_FRACTION_DIGITS) {
            throw new IllegalArgumentException("fractionDigits must be between 0 and " + MAX_FRACTION_DIGITS);
        }
    }
}
