package interview;

import java.util.Objects;

/** A correct equals/hashCode pair on a hand-written immutable class (a record would generate these). */
public final class Money {
    private final long cents;
    private final String currency;

    public Money(long cents, String currency) {
        this.cents = cents;
        this.currency = Objects.requireNonNull(currency);
    }

    public long cents() { return cents; }
    public String currency() { return currency; }

    public Money plus(Money other) {
        if (!currency.equals(other.currency)) throw new IllegalArgumentException("currency mismatch");
        return new Money(Math.addExact(cents, other.cents), currency); // new object: immutability
    }

    @Override public boolean equals(Object o) {
        return o instanceof Money m && cents == m.cents && currency.equals(m.currency);
    }

    @Override public int hashCode() { return Objects.hash(cents, currency); }

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