package dev.lions.unionflow.server.resource.gouvernance;

import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.*;

import dev.lions.unionflow.server.entity.Organisation;
import dev.lions.unionflow.server.entity.gouvernance.EchelonOrganigramme;
import dev.lions.unionflow.server.repository.OrganisationRepository;
import dev.lions.unionflow.server.repository.gouvernance.EchelonOrganigrammeRepository;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.security.TestSecurity;
import io.restassured.http.ContentType;
import jakarta.inject.Inject;
import jakarta.transaction.Transactional;
import java.time.LocalDateTime;
import java.util.UUID;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;

@QuarkusTest
class EchelonOrganigrammeResourceTest {

    @Inject
    OrganisationRepository organisationRepository;

    @Inject
    EchelonOrganigrammeRepository echelonOrganigrammeRepository;

    private Organisation testOrganisation;
    private EchelonOrganigramme testEchelon;

    @BeforeEach
    @Transactional
    void setupTestData() {
        testOrganisation = new Organisation();
        testOrganisation.setNom("Org Echelon Resource Test " + UUID.randomUUID().toString().substring(0, 6));
        testOrganisation.setTypeOrganisation("ASSOCIATION");
        testOrganisation.setStatut("ACTIVE");
        testOrganisation.setEmail("echelon-res-" + UUID.randomUUID() + "@test.com");
        testOrganisation.setActif(true);
        testOrganisation.setDateCreation(LocalDateTime.now());
        organisationRepository.persist(testOrganisation);

        testEchelon = new EchelonOrganigramme();
        testEchelon.setOrganisation(testOrganisation);
        testEchelon.setNiveau(dev.lions.unionflow.server.api.enums.gouvernance.NiveauEchelon.NATIONAL);
        testEchelon.setDesignation("Echelon Test National");
        testEchelon.setActif(true);
        testEchelon.setDateCreation(LocalDateTime.now());
        echelonOrganigrammeRepository.persist(testEchelon);
    }

    @AfterEach
    @Transactional
    void cleanupTestData() {
        if (testEchelon != null && testEchelon.getId() != null) {
            echelonOrganigrammeRepository.deleteById(testEchelon.getId());
        }
        if (testOrganisation != null && testOrganisation.getId() != null) {
            organisationRepository.deleteById(testOrganisation.getId());
        }
    }

    @Test
    @TestSecurity(user = "admin@unionflow.com", roles = { "ADMIN", "ADMIN_ORGANISATION" })
    @DisplayName("GET /api/v1/gouvernance/organigramme/{id} inexistant retourne 404")
    void getEchelonById_inexistant_returns404() {
        given()
                .pathParam("id", UUID.randomUUID())
                .when()
                .get("/api/v1/gouvernance/organigramme/{id}")
                .then()
                .statusCode(404);
    }

    @Test
    @TestSecurity(user = "admin@unionflow.com", roles = { "ADMIN", "ADMIN_ORGANISATION", "MEMBRE" })
    @DisplayName("GET /api/v1/gouvernance/organigramme/{id} existant retourne 200")
    void getEchelonById_existant_returns200() {
        given()
                .pathParam("id", testEchelon.getId())
                .when()
                .get("/api/v1/gouvernance/organigramme/{id}")
                .then()
                .statusCode(200)
                .body("id", notNullValue());
    }

    @Test
    @TestSecurity(user = "admin@unionflow.com", roles = { "ADMIN", "ADMIN_ORGANISATION" })
    @DisplayName("GET /api/v1/gouvernance/organigramme/organisation/{id} retourne 200")
    void getOrganigrammeByOrganisation_returns200() {
        given()
                .pathParam("organisationId", UUID.randomUUID())
                .when()
                .get("/api/v1/gouvernance/organigramme/organisation/{organisationId}")
                .then()
                .statusCode(200)
                .body("$", notNullValue());
    }

    @Test
    @TestSecurity(user = "admin@unionflow.com", roles = { "ADMIN", "ADMIN_ORGANISATION" })
    @DisplayName("POST creerEchelon avec organisation valide retourne 201")
    void creerEchelon_valid_returns201() {
        String body = "{"
                + "\"organisationId\": \"" + testOrganisation.getId() + "\","
                + "\"niveau\": \"NATIONAL\","
                + "\"designation\": \"Echelon POST Test\""
                + "}";
        String echelonId = given()
                .contentType(ContentType.JSON)
                .body(body)
                .when()
                .post("/api/v1/gouvernance/organigramme")
                .then()
                .statusCode(201)
                .body("id", notNullValue())
                .extract().path("id");

        // Cleanup the created echelon
        if (echelonId != null) {
            try {
                cleanupEchelon(UUID.fromString(echelonId));
            } catch (Exception e) {
                // best effort cleanup
            }
        }
    }

    @Transactional
    void cleanupEchelon(UUID id) {
        echelonOrganigrammeRepository.deleteById(id);
    }

    @Test
    @TestSecurity(user = "admin@unionflow.com", roles = { "ADMIN", "ADMIN_ORGANISATION" })
    @DisplayName("POST creerEchelon avec corps vide retourne 4xx")
    void creerEchelon_corpsVide_returns4xx() {
        given()
                .contentType(ContentType.JSON)
                .body("{}")
                .when()
                .post("/api/v1/gouvernance/organigramme")
                .then()
                .statusCode(anyOf(equalTo(400), equalTo(500)));
    }
}
