package com.cameleer.server.app.license;

import com.cameleer.server.app.AbstractPostgresIT;
import com.cameleer.server.app.TestSecurityHelper;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;

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

/**
 * Verifies that the {@code max_apps} cap from the default tier is enforced at
 * {@code POST /api/v1/environments/{envSlug}/apps}. Default tier {@code max_apps = 3}; with no
 * license installed the gate is in {@link com.cameleer.server.core.license.LicenseState#ABSENT}
 * and the defaults are authoritative. The fourth create attempt must be rejected with the
 * structured 403 envelope produced by {@link LicenseExceptionAdvice}.
 */
class AppCapEnforcementIT extends AbstractPostgresIT {

    @Autowired
    private TestRestTemplate restTemplate;

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private TestSecurityHelper securityHelper;

    private String adminJwt;

    @BeforeEach
    void setUp() {
        adminJwt = securityHelper.adminToken();
        // Defensive: a sibling IT may have left a license installed (LicenseGate is a singleton
        // per Spring context; @SpringBootTest reuses contexts across ITs).
        securityHelper.clearTestLicense();
        // Strip dependents first, then the apps themselves. Keep the seeded "default" environment.
        jdbcTemplate.update("DELETE FROM deployments");
        jdbcTemplate.update("DELETE FROM app_versions");
        jdbcTemplate.update("DELETE FROM apps");
    }

    @AfterEach
    void tearDown() {
        // Defensive cleanup — we never installed a license, but make sure later ITs see ABSENT.
        securityHelper.clearTestLicense();
        jdbcTemplate.update("DELETE FROM deployments");
        jdbcTemplate.update("DELETE FROM app_versions");
        jdbcTemplate.update("DELETE FROM apps");
    }

    @Test
    void createBeyondCap_returns403WithStateAndMessage() throws Exception {
        // Default tier: max_apps = 3. Three creates succeed; the fourth rejects.
        for (int i = 1; i <= 3; i++) {
            String json = String.format("""
                    {"slug":"a%d","displayName":"A%d"}
                    """, i, i);
            ResponseEntity<String> ok = restTemplate.exchange(
                    "/api/v1/environments/default/apps", HttpMethod.POST,
                    new HttpEntity<>(json, securityHelper.authHeaders(adminJwt)),
                    String.class);
            assertThat(ok.getStatusCode())
                    .as("create #%d should succeed", i)
                    .isEqualTo(HttpStatus.CREATED);
        }

        String fourth = """
                {"slug":"a4","displayName":"A4"}
                """;
        ResponseEntity<String> response = restTemplate.exchange(
                "/api/v1/environments/default/apps", HttpMethod.POST,
                new HttpEntity<>(fourth, securityHelper.authHeaders(adminJwt)),
                String.class);

        assertThat(response.getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN);
        JsonNode body = objectMapper.readTree(response.getBody());
        assertThat(body.path("error").asText()).isEqualTo("license cap reached");
        assertThat(body.path("limit").asText()).isEqualTo("max_apps");
        assertThat(body.path("cap").asInt()).isEqualTo(3);
        assertThat(body.path("state").asText()).isEqualTo("ABSENT");
        assertThat(body.has("message")).isTrue();
        assertThat(body.path("message").asText()).isNotBlank();

        // And the fourth app was not persisted.
        Integer count = jdbcTemplate.queryForObject(
                "SELECT COUNT(*) FROM apps WHERE slug = 'a4'", Integer.class);
        assertThat(count).isZero();
    }
}
