package com.cameleer.server.app.controller;

import com.cameleer.server.app.AbstractPostgresIT;
import com.cameleer.server.app.TestSecurityHelper;
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.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;

import java.util.Map;

import static java.util.concurrent.TimeUnit.SECONDS;
import static org.assertj.core.api.Assertions.assertThat;
import static org.awaitility.Awaitility.await;

class DiagramControllerIT extends AbstractPostgresIT {

    @Autowired
    private TestRestTemplate restTemplate;

    @Autowired
    private TestSecurityHelper securityHelper;

    private HttpHeaders authHeaders;
    private HttpHeaders viewerHeaders;

    @BeforeEach
    void setUp() {
        // Lift max_agents cap so this IT (which registers an agent) isn't gated by license
        // enforcement. Cap behaviour itself is exercised by AgentCapEnforcementIT.
        securityHelper.installSyntheticUnsignedLicense(Map.of("max_agents", 100));
        String jwt = securityHelper.registerTestAgent("test-agent-diagram-it");
        authHeaders = securityHelper.authHeaders(jwt);
        viewerHeaders = securityHelper.authHeadersNoBody(securityHelper.viewerToken());
    }

    @AfterEach
    void tearDown() {
        securityHelper.clearTestLicense();
    }

    @Test
    void postSingleDiagram_returns202() {
        String json = """
                {
                  "routeId": "diagram-route-1",
                  "description": "Test route",
                  "version": 1,
                  "nodes": [],
                  "edges": []
                }
                """;

        ResponseEntity<String> response = restTemplate.postForEntity(
                "/api/v1/data/diagrams",
                new HttpEntity<>(json, authHeaders),
                String.class);

        assertThat(response.getStatusCode()).isEqualTo(HttpStatus.ACCEPTED);
    }

    @Test
    void postDiagram_dataAppearsAfterFlush() {
        String json = """
                {
                  "routeId": "diagram-flush-route",
                  "description": "Flush test",
                  "version": 1,
                  "nodes": [],
                  "edges": []
                }
                """;

        restTemplate.postForEntity(
                "/api/v1/data/diagrams",
                new HttpEntity<>(json, authHeaders),
                String.class);

        // route_diagrams lives in ClickHouse; drive the visibility check
        // through the env-scoped diagram-render endpoint, never raw SQL.
        await().atMost(15, SECONDS).untilAsserted(() -> {
            ResponseEntity<String> r = restTemplate.exchange(
                    "/api/v1/environments/default/apps/test-group/routes/diagram-flush-route/diagram",
                    HttpMethod.GET,
                    new HttpEntity<>(viewerHeaders),
                    String.class);
            assertThat(r.getStatusCode()).isEqualTo(HttpStatus.OK);
        });
    }

    @Test
    void postArrayOfDiagrams_returns202() {
        String json = """
                [{
                  "routeId": "diagram-arr-1",
                  "version": 1,
                  "nodes": [],
                  "edges": []
                },
                {
                  "routeId": "diagram-arr-2",
                  "version": 1,
                  "nodes": [],
                  "edges": []
                }]
                """;

        ResponseEntity<String> response = restTemplate.postForEntity(
                "/api/v1/data/diagrams",
                new HttpEntity<>(json, authHeaders),
                String.class);

        assertThat(response.getStatusCode()).isEqualTo(HttpStatus.ACCEPTED);
    }
}
