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_outbound_connections} cap from the default tier is enforced at
 * {@code POST /api/v1/admin/outbound-connections}. Default tier
 * {@code max_outbound_connections = 1}; with no license installed the gate is in
 * {@link com.cameleer.server.core.license.LicenseState#ABSENT} and the defaults are
 * authoritative. The first create succeeds; the second must be rejected with the structured
 * 403 envelope produced by {@link LicenseExceptionAdvice}.
 */
class OutboundCapEnforcementIT 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 outbound_connections so we start at zero — the cap is per-tenant.
        jdbcTemplate.update("DELETE FROM outbound_connections");
        // Seed user row for the JWT subject — outbound_connections.created_by FKs to users(user_id).
        jdbcTemplate.update(
                "INSERT INTO users (user_id, provider, email, display_name) VALUES (?, 'test', ?, ?) ON CONFLICT (user_id) DO NOTHING",
                "test-admin", "test-admin@example.com", "test-admin");
    }

    @AfterEach
    void tearDown() {
        // Defensive cleanup — we never installed a license, but make sure later ITs see ABSENT.
        securityHelper.clearTestLicense();
        jdbcTemplate.update("DELETE FROM outbound_connections");
        jdbcTemplate.update("DELETE FROM users WHERE user_id = 'test-admin'");
    }

    @Test
    void createBeyondCap_returns403WithStateAndMessage() throws Exception {
        // Default tier: max_outbound_connections = 1. First create succeeds; the second rejects.
        String first = """
                {"name":"hook-1","url":"https://hooks.example.com/1","method":"POST",
                 "tlsTrustMode":"SYSTEM_DEFAULT","auth":{}}""";
        ResponseEntity<String> ok = restTemplate.exchange(
                "/api/v1/admin/outbound-connections", HttpMethod.POST,
                new HttpEntity<>(first, securityHelper.authHeaders(adminJwt)),
                String.class);
        assertThat(ok.getStatusCode()).isEqualTo(HttpStatus.CREATED);

        String second = """
                {"name":"hook-2","url":"https://hooks.example.com/2","method":"POST",
                 "tlsTrustMode":"SYSTEM_DEFAULT","auth":{}}""";
        ResponseEntity<String> response = restTemplate.exchange(
                "/api/v1/admin/outbound-connections", HttpMethod.POST,
                new HttpEntity<>(second, 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_outbound_connections");
        assertThat(body.path("cap").asInt()).isEqualTo(1);
        assertThat(body.path("state").asText()).isEqualTo("ABSENT");
        assertThat(body.has("message")).isTrue();
        assertThat(body.path("message").asText()).isNotBlank();

        // And the second connection was NOT persisted.
        Integer count = jdbcTemplate.queryForObject(
                "SELECT COUNT(*) FROM outbound_connections WHERE name = 'hook-2'", Integer.class);
        assertThat(count).isZero();

        // Total connections still 1 — the rejection short-circuited before any insert.
        Integer total = jdbcTemplate.queryForObject(
                "SELECT COUNT(*) FROM outbound_connections", Integer.class);
        assertThat(total).isEqualTo(1);
    }
}
