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 java.util.Map;

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

/**
 * Integration test for forward compatibility (API-05).
 * Verifies that unknown JSON fields in request bodies do not cause deserialization errors.
 */
class ForwardCompatIT extends AbstractPostgresIT {

    @Autowired
    private TestRestTemplate restTemplate;

    @Autowired
    private TestSecurityHelper securityHelper;

    private String jwt;

    @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));
        jwt = securityHelper.registerTestAgent("test-agent-forward-compat-it");
    }

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

    @Test
    void unknownFieldsInRequestBodyDoNotCauseError() {
        // Valid ExecutionChunk plus extra fields a future agent version
        // might send. Jackson is configured with FAIL_ON_UNKNOWN_PROPERTIES
        // = false on ChunkIngestionController, so the extras must be ignored
        // and the envelope accepted with 202.
        String jsonWithUnknownFields = """
                {
                  "exchangeId": "fwd-compat-1",
                  "applicationId": "test-group",
                  "instanceId": "test-agent-forward-compat-it",
                  "routeId": "fwd-compat-route",
                  "status": "COMPLETED",
                  "startTime": "2026-03-11T10:00:00Z",
                  "endTime": "2026-03-11T10:00:01Z",
                  "durationMs": 1000,
                  "chunkSeq": 0,
                  "final": true,
                  "processors": [],
                  "futureField": "value",
                  "anotherUnknown": 42,
                  "someNested": {"key": "v"}
                }
                """;

        HttpHeaders headers = securityHelper.authHeaders(jwt);
        var entity = new HttpEntity<>(jsonWithUnknownFields, headers);

        var response = restTemplate.exchange(
                "/api/v1/data/executions", HttpMethod.POST, entity, String.class);

        assertThat(response.getStatusCode().value())
                .as("Unknown JSON fields must not cause 400 or 422 deserialization error")
                .isNotIn(400, 422);
    }
}
