package at.procon.eventhub.dto;

import at.procon.eventhub.reference.TachographNationRegistry;

/**
 * Vehicle registration number reference. VRN/plate is scoped by nation and can
 * be resolved historically by occurredAt later.
 */
public record VehicleRegistrationRefDto(
        String nation,
        Integer nationNumericCode,
        String number
) {
    public VehicleRegistrationRefDto(String nation, String number) {
        this(nation, null, number);
    }

    public VehicleRegistrationRefDto {
        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 value == null || value.isBlank() ? null : value.trim();
    }
}
