package at.procon.eventhub.dto;

import at.procon.eventhub.reference.DriverCardNumberNormalizer;
import at.procon.eventhub.reference.TachographNationRegistry;

/**
 * Tachograph driver-card identifier. The card number is scoped by issuing nation.
 */
public record DriverCardRefDto(
        String nation,
        Integer nationNumericCode,
        String number
) {
    public DriverCardRefDto(String nation, String number) {
        this(nation, null, number);
    }

    public DriverCardRefDto {
        TachographNationRegistry.NationResolution nationResolution =
                TachographNationRegistry.resolve(nation, nationNumericCode);
        nation = normalize(nationResolution.legacyNation());
        nationNumericCode = nationResolution.numericCode();
        number = normalizeNullable(number);
    }

    public boolean hasValue() {
        return number != null && !number.isBlank();
    }

    public String stableKey() {
        String nationKey = nationNumericCode == null ? nation : String.valueOf(nationNumericCode);
        return (nationKey == null ? "" : nationKey) + ":" + (number == null ? "" : number);
    }

    private static String normalize(String value) {
        if (value == null || value.isBlank()) {
            return null;
        }
        String trimmed = value.trim();
        if (trimmed.matches("(?i)^unknown\\s+[0-9]+$")) {
            return "Unknown " + trimmed.replaceAll("[^0-9]", "");
        }
        return trimmed.toUpperCase();
    }

    private static String normalizeNullable(String value) {
        return DriverCardNumberNormalizer.canonical(value);
    }
}
