package at.procon.eventhub.processing.model;

public record UnifiedDiscoveredVehicleRef(
        String sourceVehicleEntityId,
        String vin,
        String registrationNation,
        String registrationNumber
) {
    public UnifiedDiscoveredVehicleRef {
        sourceVehicleEntityId = normalize(sourceVehicleEntityId);
        vin = normalizeUpper(vin);
        registrationNation = normalizeUpper(registrationNation);
        registrationNumber = normalize(registrationNumber);
    }

    public boolean hasAnyReference() {
        return sourceVehicleEntityId != null || vin != null || registrationNumber != null;
    }

    public boolean matches(UnifiedDiscoveredVehicleRef other) {
        if (other == null) {
            return false;
        }
        return same(sourceVehicleEntityId, other.sourceVehicleEntityId)
                || same(vin, other.vin)
                || (same(registrationNumber, other.registrationNumber)
                && same(registrationNation, other.registrationNation));
    }

    public UnifiedDiscoveredVehicleRef merge(UnifiedDiscoveredVehicleRef other) {
        if (other == null) {
            return this;
        }
        return new UnifiedDiscoveredVehicleRef(
                firstNonBlank(sourceVehicleEntityId, other.sourceVehicleEntityId),
                firstNonBlank(vin, other.vin),
                firstNonBlank(registrationNation, other.registrationNation),
                firstNonBlank(registrationNumber, other.registrationNumber)
        );
    }

    public String stableKey() {
        if (sourceVehicleEntityId != null) {
            return "SOURCE_VEHICLE:" + sourceVehicleEntityId;
        }
        if (vin != null) {
            return "VIN:" + vin;
        }
        return "REG:" + (registrationNation == null ? "" : registrationNation) + ":" + (registrationNumber == null ? "" : registrationNumber);
    }

    private boolean same(String left, String right) {
        return left != null && right != null && left.equals(right);
    }

    private static String firstNonBlank(String first, String second) {
        if (first != null && !first.isBlank()) {
            return first;
        }
        return second != null && !second.isBlank() ? second : null;
    }

    private static String normalize(String value) {
        return value == null || value.isBlank() ? null : value.trim();
    }

    private static String normalizeUpper(String value) {
        return value == null || value.isBlank() ? null : value.trim().toUpperCase();
    }
}
