package com.cameleer.server.app.license;

import com.cameleer.server.core.license.LicenseGate;
import com.cameleer.server.core.license.LicenseInfo;
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;
import static org.assertj.core.api.Assertions.assertThatThrownBy;

class LicenseEnforcerTest {

    @Test
    void underCap_passes() {
        LicenseGate gate = new LicenseGate();
        gate.load(license(Map.of("max_apps", 10), 0));
        new LicenseEnforcer(gate).assertWithinCap("max_apps", 9, 1);
    }

    @Test
    void atCap_throws() {
        LicenseGate gate = new LicenseGate();
        gate.load(license(Map.of("max_apps", 10), 0));
        assertThatThrownBy(() -> new LicenseEnforcer(gate).assertWithinCap("max_apps", 10, 1))
                .isInstanceOf(LicenseCapExceededException.class)
                .hasMessageContaining("max_apps");
    }

    @Test
    void absent_usesDefaultTier() {
        LicenseGate gate = new LicenseGate();
        // default max_apps = 3; current 3 + 1 > 3 -> reject
        assertThatThrownBy(() -> new LicenseEnforcer(gate).assertWithinCap("max_apps", 3, 1))
                .isInstanceOf(LicenseCapExceededException.class);
    }

    @Test
    void unknownLimitKey_throwsIllegalArgument() {
        LicenseGate gate = new LicenseGate();
        assertThatThrownBy(() -> new LicenseEnforcer(gate).assertWithinCap("max_xyz", 0, 1))
                .isInstanceOf(IllegalArgumentException.class);
    }

    private LicenseInfo license(Map<String, Integer> limits, int grace) {
        return new LicenseInfo(UUID.randomUUID(), "acme", null,
                limits, Instant.now(), Instant.now().plusSeconds(86400), grace);
    }
}
