package de.effigenix.shared.common;

/**
 * Value Object representing a postal address.
 * Immutable and self-validating.
 */
public record Address(
        String street,
        String houseNumber,
        String postalCode,
        String city,
        String country
) {

    public Address {
        if (street == null || street.isBlank()) {
            throw new IllegalArgumentException("Street must not be blank");
        }
        if (postalCode == null || postalCode.isBlank()) {
            throw new IllegalArgumentException("Postal code must not be blank");
        }
        if (city == null || city.isBlank()) {
            throw new IllegalArgumentException("City must not be blank");
        }
        if (country == null || country.isBlank()) {
            throw new IllegalArgumentException("Country must not be blank");
        }
        if (!country.matches("^[A-Z]{2}$")) {
            throw new IllegalArgumentException("Country must be ISO 3166-1 alpha-2 code (e.g. 'DE')");
        }
        // houseNumber is optional (nullable)
    }

    public static Result<String, Address> create(
            String street, String houseNumber, String postalCode, String city, String country) {
        try {
            return Result.success(new Address(street, houseNumber, postalCode, city, country));
        } catch (IllegalArgumentException e) {
            return Result.failure(e.getMessage());
        }
    }
}
