package com.cameleer.server.app.controller;

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.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 static java.util.concurrent.TimeUnit.SECONDS;
import static org.assertj.core.api.Assertions.assertThat;
import static org.awaitility.Awaitility.await;

/**
 * Integration tests for {@link DiagramRenderController}. The env-scoped
 * endpoint only serves JSON — SVG rendering is only available via the
 * flat content-hash endpoint. We seed the diagram plus an execution for
 * the same route, then pull the content hash from the execution-detail
 * REST response to drive the flat-endpoint render tests.
 */
class DiagramRenderControllerIT extends AbstractPostgresIT {

    @Autowired
    private TestRestTemplate restTemplate;

    @Autowired
    private TestSecurityHelper securityHelper;

    private final ObjectMapper objectMapper = new ObjectMapper();

    private String jwt;
    private String viewerJwt;
    private String contentHash;

    @BeforeEach
    void seedDiagram() {
        jwt = securityHelper.registerTestAgent("test-agent-diagram-render-it");
        viewerJwt = securityHelper.viewerToken();

        String diagramJson = """
                {
                  "routeId": "render-test-route",
                  "description": "Render test",
                  "version": 1,
                  "nodes": [
                    {"id": "n1", "type": "ENDPOINT", "label": "timer:tick"},
                    {"id": "n2", "type": "BEAN", "label": "myBean"},
                    {"id": "n3", "type": "TO", "label": "log:out"}
                  ],
                  "edges": [
                    {"source": "n1", "target": "n2", "edgeType": "FLOW"},
                    {"source": "n2", "target": "n3", "edgeType": "FLOW"}
                  ]
                }
                """;
        restTemplate.postForEntity(
                "/api/v1/data/diagrams",
                new HttpEntity<>(diagramJson, securityHelper.authHeaders(jwt)),
                String.class);

        // Post an execution for the same route so the ingestion pipeline
        // stamps diagramContentHash on it — that's our path to fetching the
        // hash without reading route_diagrams directly.
        String execJson = """
                {
                  "exchangeId": "render-probe-exchange",
                  "applicationId": "test-group",
                  "instanceId": "test-agent-diagram-render-it",
                  "routeId": "render-test-route",
                  "correlationId": "render-probe-corr",
                  "status": "COMPLETED",
                  "startTime": "2026-03-11T10:00:00Z",
                  "endTime": "2026-03-11T10:00:01Z",
                  "durationMs": 1000,
                  "chunkSeq": 0,
                  "final": true,
                  "processors": []
                }
                """;
        restTemplate.postForEntity(
                "/api/v1/data/executions",
                new HttpEntity<>(execJson, securityHelper.authHeaders(jwt)),
                String.class);

        // Wait for both to land, then read the hash off the execution detail.
        await().atMost(20, SECONDS).untilAsserted(() -> {
            HttpHeaders headers = securityHelper.authHeadersNoBody(viewerJwt);
            ResponseEntity<String> search = restTemplate.exchange(
                    "/api/v1/environments/default/executions?correlationId=render-probe-corr",
                    HttpMethod.GET,
                    new HttpEntity<>(headers),
                    String.class);
            assertThat(search.getStatusCode()).isEqualTo(HttpStatus.OK);
            JsonNode body = objectMapper.readTree(search.getBody());
            assertThat(body.get("total").asLong()).isGreaterThanOrEqualTo(1);
            String execId = body.get("data").get(0).get("executionId").asText();

            ResponseEntity<String> detail = restTemplate.exchange(
                    "/api/v1/executions/" + execId,
                    HttpMethod.GET,
                    new HttpEntity<>(headers),
                    String.class);
            assertThat(detail.getStatusCode()).isEqualTo(HttpStatus.OK);
            JsonNode detailBody = objectMapper.readTree(detail.getBody());
            String hash = detailBody.path("diagramContentHash").asText();
            assertThat(hash).isNotEmpty();
            contentHash = hash;
        });
    }

    @Test
    void getSvg_withAcceptHeader_returnsSvg() {
        HttpHeaders headers = securityHelper.authHeadersNoBody(viewerJwt);
        headers.set("Accept", "image/svg+xml");

        ResponseEntity<String> response = restTemplate.exchange(
                "/api/v1/diagrams/{hash}/render",
                HttpMethod.GET,
                new HttpEntity<>(headers),
                String.class,
                contentHash);

        assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
        assertThat(response.getHeaders().getContentType().toString()).contains("svg");
        assertThat(response.getBody()).contains("<svg");
    }

    @Test
    void getJson_withAcceptHeader_returnsJson() {
        HttpHeaders headers = securityHelper.authHeadersNoBody(viewerJwt);
        headers.set("Accept", "application/json");

        ResponseEntity<String> response = restTemplate.exchange(
                "/api/v1/diagrams/{hash}/render",
                HttpMethod.GET,
                new HttpEntity<>(headers),
                String.class,
                contentHash);

        assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
        assertThat(response.getBody()).contains("nodes");
        assertThat(response.getBody()).contains("edges");
    }

    @Test
    void getNonExistentHash_returns404() {
        // Only test the flat content-hash endpoint here — 404 on bogus hash
        // doesn't need a valid hash, so no SQL lookup is required.
        HttpHeaders headers = securityHelper.authHeadersNoBody(viewerJwt);
        headers.set("Accept", "image/svg+xml");

        ResponseEntity<String> response = restTemplate.exchange(
                "/api/v1/diagrams/{hash}/render",
                HttpMethod.GET,
                new HttpEntity<>(headers),
                String.class,
                "nonexistent-hash-12345");

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

    @Test
    void getWithNoAcceptHeader_defaultsToSvg() {
        HttpHeaders headers = securityHelper.authHeadersNoBody(viewerJwt);

        ResponseEntity<String> response = restTemplate.exchange(
                "/api/v1/diagrams/{hash}/render",
                HttpMethod.GET,
                new HttpEntity<>(headers),
                String.class,
                contentHash);

        assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
        assertThat(response.getBody()).contains("<svg");
    }
}
