package com.cameleer.server.app.license;

import com.cameleer.server.app.AbstractPostgresIT;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;

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

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

class PostgresLicenseRepositoryIT extends AbstractPostgresIT {

    @Autowired LicenseRepository repo;

    @Test
    void roundTrip() {
        UUID id = UUID.randomUUID();
        Instant now = Instant.now().truncatedTo(ChronoUnit.MILLIS);
        LicenseRecord rec = new LicenseRecord(
                "default", "tok.sig", id, now, "system",
                now.plus(365, ChronoUnit.DAYS), now);
        repo.upsert(rec);

        var loaded = repo.findByTenantId("default").orElseThrow();
        assertThat(loaded.licenseId()).isEqualTo(id);
        assertThat(loaded.installedBy()).isEqualTo("system");
    }

    @Test
    void touchValidated_updatesTimestamp() throws Exception {
        UUID id = UUID.randomUUID();
        Instant t0 = Instant.now().truncatedTo(ChronoUnit.MILLIS);
        repo.upsert(new LicenseRecord("default", "tok.sig", id, t0, "system",
                t0.plus(7, ChronoUnit.DAYS), t0));

        Thread.sleep(10);
        Instant t1 = Instant.now().truncatedTo(ChronoUnit.MILLIS);
        int affected = repo.touchValidated("default", t1);
        assertThat(affected).isEqualTo(1);
        assertThat(repo.findByTenantId("default").orElseThrow().lastValidatedAt())
                .isAfterOrEqualTo(t1);
    }
}
