package io.cameleer.server.app.license;

import io.cameleer.server.core.license.LicenseGate;
import io.cameleer.license.LicenseInfo;
import io.micrometer.core.instrument.simple.SimpleMeterRegistry;
import org.junit.jupiter.api.Test;

import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;

import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

class LicenseMetricsTest {

    @Test
    void absentState_setsAbsentGaugeTo1AndDaysRemainingTo_minusOne() {
        LicenseGate gate = new LicenseGate();
        LicenseRepository repo = mock(LicenseRepository.class);
        when(repo.findByTenantId("default")).thenReturn(Optional.empty());
        SimpleMeterRegistry meters = new SimpleMeterRegistry();

        var metrics = new LicenseMetrics(gate, repo, meters, "default");
        metrics.refresh();

        assertThat(meters.find("cameleer_license_state").tag("state", "ABSENT").gauge().value())
                .isEqualTo(1.0);
        assertThat(meters.find("cameleer_license_state").tag("state", "ACTIVE").gauge().value())
                .isEqualTo(0.0);
        assertThat(meters.find("cameleer_license_days_remaining").gauge().value())
                .isEqualTo(-1.0);
    }

    @Test
    void activeState_reportsDaysRemaining() {
        LicenseGate gate = new LicenseGate();
        gate.load(new LicenseInfo(UUID.randomUUID(), "default", "test",
                Map.of(),
                Instant.now().minusSeconds(86400),
                Instant.now().plus(10, ChronoUnit.DAYS),
                0));
        LicenseRepository repo = mock(LicenseRepository.class);
        when(repo.findByTenantId("default")).thenReturn(Optional.empty());
        SimpleMeterRegistry meters = new SimpleMeterRegistry();

        var metrics = new LicenseMetrics(gate, repo, meters, "default");
        metrics.refresh();

        assertThat(meters.find("cameleer_license_state").tag("state", "ACTIVE").gauge().value())
                .isEqualTo(1.0);
        assertThat(meters.find("cameleer_license_state").tag("state", "ABSENT").gauge().value())
                .isEqualTo(0.0);
        assertThat(meters.find("cameleer_license_days_remaining").gauge().value())
                .isBetween(9.0, 10.5);
    }
}
