package com.cameleer.server.core.license;

import org.junit.jupiter.api.Test;

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

import static org.assertj.core.api.Assertions.assertThat;

class LicenseGateTest {

    @Test
    void absent_byDefault() {
        LicenseGate gate = new LicenseGate();
        assertThat(gate.getState()).isEqualTo(LicenseState.ABSENT);
        assertThat(gate.getEffectiveLimits().get("max_apps"))
                .isEqualTo(DefaultTierLimits.DEFAULTS.get("max_apps"));
        assertThat(gate.getCurrent()).isNull();
        assertThat(gate.getInvalidReason()).isNull();
    }

    @Test
    void load_setsActiveAndMergesLimits() {
        LicenseGate gate = new LicenseGate();
        LicenseInfo info = new LicenseInfo(UUID.randomUUID(), "acme", "label",
                Map.of("max_apps", 50), Instant.now(),
                Instant.now().plusSeconds(86400), 0);
        gate.load(info);

        assertThat(gate.getState()).isEqualTo(LicenseState.ACTIVE);
        assertThat(gate.getEffectiveLimits().get("max_apps")).isEqualTo(50);
        assertThat(gate.getEffectiveLimits().get("max_users"))
                .isEqualTo(DefaultTierLimits.DEFAULTS.get("max_users"));
    }

    @Test
    void markInvalid_overridesActive() {
        LicenseGate gate = new LicenseGate();
        LicenseInfo info = new LicenseInfo(UUID.randomUUID(), "acme", null,
                Map.of("max_apps", 50), Instant.now(),
                Instant.now().plusSeconds(86400), 0);
        gate.load(info);

        gate.markInvalid("signature failed");
        assertThat(gate.getState()).isEqualTo(LicenseState.INVALID);
        assertThat(gate.getEffectiveLimits().get("max_apps"))
                .isEqualTo(DefaultTierLimits.DEFAULTS.get("max_apps"));
        assertThat(gate.getInvalidReason()).isEqualTo("signature failed");
    }

    @Test
    void clear_returnsToAbsent() {
        LicenseGate gate = new LicenseGate();
        LicenseInfo info = new LicenseInfo(UUID.randomUUID(), "acme", null,
                Map.of(), Instant.now(),
                Instant.now().plusSeconds(86400), 0);
        gate.load(info);
        gate.clear();

        assertThat(gate.getState()).isEqualTo(LicenseState.ABSENT);
        assertThat(gate.getCurrent()).isNull();
    }
}
