package com.cameleer.server.app.outbound.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.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.TestPropertySource;

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

/**
 * Dedicated IT that overrides the test-profile default `allow-private-targets=true`
 * back to `false` so the SSRF guard's production behavior (reject loopback) is
 * exercised end-to-end through the admin controller.
 *
 * Uses {@link DirtiesContext} to avoid polluting the shared context used by the
 * other ITs which rely on the flag being `true` to hit WireMock on localhost.
 */
@TestPropertySource(properties = "cameleer.server.outbound-http.allow-private-targets=false")
@DirtiesContext
class OutboundConnectionSsrfIT extends AbstractPostgresIT {

    @Autowired private TestRestTemplate restTemplate;
    @Autowired private TestSecurityHelper securityHelper;

    private String adminJwt;

    @BeforeEach
    void setUp() {
        adminJwt = securityHelper.adminToken();
        // Seed admin user row since users(user_id) is an FK target.
        jdbcTemplate.update(
                "INSERT INTO users (user_id, provider, email, display_name) VALUES (?, 'test', ?, ?) ON CONFLICT (user_id) DO NOTHING",
                "test-admin", "test-admin@example.com", "test-admin");
        jdbcTemplate.update("DELETE FROM outbound_connections WHERE tenant_id = 'default'");
    }

    @AfterEach
    void cleanup() {
        jdbcTemplate.update("DELETE FROM outbound_connections WHERE tenant_id = 'default'");
        jdbcTemplate.update("DELETE FROM users WHERE user_id = 'test-admin'");
    }

    @Test
    void rejectsLoopbackUrlOnCreate() {
        String body = """
                {"name":"evil","url":"https://127.0.0.1/abuse","method":"POST",
                 "tlsTrustMode":"SYSTEM_DEFAULT","auth":{}}""";

        ResponseEntity<String> resp = restTemplate.exchange(
                "/api/v1/admin/outbound-connections", HttpMethod.POST,
                new HttpEntity<>(body, securityHelper.authHeaders(adminJwt)),
                String.class);

        assertThat(resp.getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST);
        assertThat(resp.getBody()).isNotNull();
        assertThat(resp.getBody()).contains("private or loopback");
    }
}
