package com.cameleer.server.core.license;

import java.time.Instant;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;

/** A parsed and signature-verified license. Construct via {@link LicenseValidator}. */
public record LicenseInfo(
        UUID licenseId,
        String tenantId,
        String label,
        Map<String, Integer> limits,
        Instant issuedAt,
        Instant expiresAt,
        int gracePeriodDays
) {
    public LicenseInfo {
        Objects.requireNonNull(licenseId, "licenseId is required");
        Objects.requireNonNull(tenantId, "tenantId is required");
        Objects.requireNonNull(limits, "limits is required");
        Objects.requireNonNull(issuedAt, "issuedAt is required");
        Objects.requireNonNull(expiresAt, "expiresAt is required");
        if (tenantId.isBlank()) {
            throw new IllegalArgumentException("tenantId must not be blank");
        }
        if (gracePeriodDays < 0) {
            throw new IllegalArgumentException("gracePeriodDays must be >= 0");
        }
    }

    /** True iff now > expiresAt + gracePeriodDays. */
    public boolean isExpired() {
        Instant deadline = expiresAt.plusSeconds((long) gracePeriodDays * 86400);
        return Instant.now().isAfter(deadline);
    }

    /** True iff now > expiresAt (regardless of grace). Used by the state machine to distinguish ACTIVE from GRACE. */
    public boolean isAfterRawExpiry() {
        return Instant.now().isAfter(expiresAt);
    }

    public int getLimit(String key, int defaultValue) {
        return limits.getOrDefault(key, defaultValue);
    }
}
