package com.example.pricing;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/** Discount codes and the percentage they take off. */
public final class Discounts {
    private final Map<Code, BigDecimal> rates = new HashMap<>();

    public void register(String code, BigDecimal percent) {
        rates.put(new Code(code), percent);
    }

    public BigDecimal rateFor(String code) {
        return rates.getOrDefault(new Code(code), BigDecimal.ZERO);
    }

    static final class Code {
        private final String value;

        Code(String value) {
            this.value = Objects.requireNonNull(value).strip();
        }

        @Override
        public boolean equals(Object o) {
            return o instanceof Code other && value.equalsIgnoreCase(other.value);
        }

        @Override
        public int hashCode() {
            return value.toLowerCase(java.util.Locale.ROOT).hashCode();
        }
    }
}
