package com.cameleer.server.app.controller;

import com.cameleer.server.app.AbstractPostgresIT;
import com.cameleer.server.app.TestSecurityHelper;
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.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;

class ExecutionControllerIT extends AbstractPostgresIT {

    @Autowired
    private TestRestTemplate restTemplate;

    @Autowired
    private TestSecurityHelper securityHelper;

    private HttpHeaders authHeaders;

    @BeforeEach
    void setUp() {
        String jwt = securityHelper.registerTestAgent("test-agent-execution-it");
        authHeaders = securityHelper.authHeaders(jwt);
    }

    @Test
    void postSingleExecution_returns202() {
        String json = """
                {
                  "routeId": "route-1",
                  "exchangeId": "exchange-1",
                  "correlationId": "corr-1",
                  "status": "COMPLETED",
                  "startTime": "2026-03-11T10:00:00Z",
                  "endTime": "2026-03-11T10:00:01Z",
                  "durationMs": 1000,
                  "errorMessage": "",
                  "errorStackTrace": "",
                  "processors": []
                }
                """;

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

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

    @Test
    void postArrayOfExecutions_returns202() {
        String json = """
                [{
                  "routeId": "route-2",
                  "exchangeId": "exchange-2",
                  "status": "COMPLETED",
                  "startTime": "2026-03-11T10:00:00Z",
                  "endTime": "2026-03-11T10:00:01Z",
                  "durationMs": 1000,
                  "processors": []
                },
                {
                  "routeId": "route-3",
                  "exchangeId": "exchange-3",
                  "status": "FAILED",
                  "startTime": "2026-03-11T10:00:00Z",
                  "endTime": "2026-03-11T10:00:02Z",
                  "durationMs": 2000,
                  "errorMessage": "Something went wrong",
                  "processors": []
                }]
                """;

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

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

    @Test
    void postExecution_dataAppearsAfterFlush() {
        String json = """
                {
                  "routeId": "flush-test-route",
                  "exchangeId": "flush-exchange-1",
                  "correlationId": "flush-corr-1",
                  "status": "COMPLETED",
                  "startTime": "2026-03-11T10:00:00Z",
                  "endTime": "2026-03-11T10:00:01Z",
                  "durationMs": 1000,
                  "processors": []
                }
                """;

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

        await().atMost(10, SECONDS).untilAsserted(() -> {
            Integer count = jdbcTemplate.queryForObject(
                    "SELECT count(*) FROM executions WHERE route_id = 'flush-test-route'",
                    Integer.class);
            assertThat(count).isGreaterThanOrEqualTo(1);
        });
    }

    @Test
    void postExecution_unknownFieldsAccepted() {
        String json = """
                {
                  "routeId": "route-unk",
                  "exchangeId": "exchange-unk",
                  "status": "COMPLETED",
                  "startTime": "2026-03-11T10:00:00Z",
                  "durationMs": 500,
                  "unknownField": "should-be-ignored",
                  "anotherUnknown": 42,
                  "processors": []
                }
                """;

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

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