/** Un monto de dinero en céntimos, con su moneda (el record de la semana 3). */
public record Money(long cents, String currency) {

    public Money {
        if (cents < 0) {
            throw new IllegalArgumentException("monto negativo: " + cents);
        }
        if (currency == null || currency.isBlank()) {
            throw new IllegalArgumentException("falta la moneda");
        }
    }

    /**
     * Convierte un texto como "12.50" en soles. Si el texto no es un número,
     * Long.parseLong lanza NumberFormatException y este método la deja pasar.
     */
    public static Money parse(String text) {
        String[] parts = text.trim().split("\\.", -1);
        long soles = Long.parseLong(parts[0]);
        long cents = 0;
        if (parts.length == 2 && parts[1].length() == 2) {
            cents = Long.parseLong(parts[1]);
        } else if (parts.length != 1) {
            throw new NumberFormatException("formato inválido: \"" + text + "\"");
        }
        return new Money(soles * 100 + cents, "PEN");
    }

    @Override
    public String toString() {
        return String.format("%s %d.%02d", currency, cents / 100, cents % 100);
    }
}
