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.*;

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

class ClaimMappingAdminControllerIT extends AbstractPostgresIT {

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

    private HttpHeaders adminHeaders;

    @BeforeEach
    void setUp() {
        adminHeaders = securityHelper.adminHeaders();
    }

    @Test
    void createAndListRules() throws Exception {
        String body = """
                {"claim":"groups","matchType":"contains","matchValue":"admins","action":"assignRole","target":"ADMIN","priority":0}
                """;
        var createResponse = restTemplate.exchange("/api/v1/admin/claim-mappings",
                HttpMethod.POST, new HttpEntity<>(body, adminHeaders), String.class);
        assertThat(createResponse.getStatusCode()).isEqualTo(HttpStatus.CREATED);

        var listResponse = restTemplate.exchange("/api/v1/admin/claim-mappings",
                HttpMethod.GET, new HttpEntity<>(adminHeaders), String.class);
        assertThat(listResponse.getStatusCode()).isEqualTo(HttpStatus.OK);

        JsonNode rules = objectMapper.readTree(listResponse.getBody());
        assertThat(rules.isArray()).isTrue();
        assertThat(rules.size()).isGreaterThanOrEqualTo(1);
    }

    @Test
    void deleteRule() throws Exception {
        String body = """
                {"claim":"dept","matchType":"equals","matchValue":"eng","action":"assignRole","target":"VIEWER","priority":0}
                """;
        var createResponse = restTemplate.exchange("/api/v1/admin/claim-mappings",
                HttpMethod.POST, new HttpEntity<>(body, adminHeaders), String.class);
        JsonNode created = objectMapper.readTree(createResponse.getBody());
        String id = created.get("id").asText();

        var deleteResponse = restTemplate.exchange("/api/v1/admin/claim-mappings/" + id,
                HttpMethod.DELETE, new HttpEntity<>(adminHeaders), Void.class);
        assertThat(deleteResponse.getStatusCode()).isEqualTo(HttpStatus.NO_CONTENT);

        var getResponse = restTemplate.exchange("/api/v1/admin/claim-mappings/" + id,
                HttpMethod.GET, new HttpEntity<>(adminHeaders), String.class);
        assertThat(getResponse.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND);
    }
}
