package de.effigenix.domain.masterdata.supplier;

import de.effigenix.shared.common.Result;

import java.time.LocalDate;

/**
 * Value Object representing a quality certificate held by a supplier.
 * Immutable, identified by content (record equality).
 */
public record QualityCertificate(
        String certificateType,
        String issuer,
        LocalDate validFrom,
        LocalDate validUntil
) {

    public QualityCertificate {
        if (certificateType == null || certificateType.isBlank()) {
            throw new IllegalArgumentException("Certificate type must not be blank");
        }
        if (validFrom != null && validUntil != null && validUntil.isBefore(validFrom)) {
            throw new IllegalArgumentException("validUntil must not be before validFrom");
        }
    }

    public static Result<String, QualityCertificate> create(
            String certificateType, String issuer, LocalDate validFrom, LocalDate validUntil) {
        try {
            return Result.success(new QualityCertificate(certificateType, issuer, validFrom, validUntil));
        } catch (IllegalArgumentException e) {
            return Result.failure(e.getMessage());
        }
    }

    public boolean isExpired() {
        return validUntil != null && validUntil.isBefore(LocalDate.now());
    }

    public boolean expiresWithinDays(int days) {
        if (validUntil == null) return false;
        return !isExpired() && validUntil.isBefore(LocalDate.now().plusDays(days));
    }
}
