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 MetricsControllerIT extends AbstractPostgresIT {

    @Autowired
    private TestRestTemplate restTemplate;

    @Autowired
    private TestSecurityHelper securityHelper;

    private HttpHeaders authHeaders;

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

    @Test
    void postMetrics_returns202() {
        String json = """
                [{
                  "instanceId": "agent-1",
                  "collectedAt": "2026-03-11T10:00:00Z",
                  "metricName": "cpu.usage",
                  "metricValue": 75.5,
                  "tags": {"host": "server-1"}
                }]
                """;

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

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

    @Test
    void postMetrics_dataAppearsAfterFlush() {
        String json = """
                [{
                  "instanceId": "agent-flush-test",
                  "collectedAt": "2026-03-11T10:00:00Z",
                  "metricName": "memory.used",
                  "metricValue": 1024.0,
                  "tags": {}
                }]
                """;

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

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