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

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

import dev.lions.unionflow.server.api.enums.ong.StatutProjetOng;
import dev.lions.unionflow.server.entity.Organisation;
import dev.lions.unionflow.server.entity.ong.ProjetOng;
import dev.lions.unionflow.server.repository.OrganisationRepository;
import dev.lions.unionflow.server.repository.ong.ProjetOngRepository;
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 ProjetOngResourceTest {

    @Inject
    OrganisationRepository organisationRepository;

    @Inject
    ProjetOngRepository projetOngRepository;

    private Organisation testOrganisation;
    private ProjetOng testProjet;

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

        testProjet = ProjetOng.builder()
                .organisation(testOrganisation)
                .nomProjet("Projet Test ONG Resource")
                .statut(StatutProjetOng.EN_ETUDE)
                .build();
        testProjet.setActif(true);
        testProjet.setDateCreation(LocalDateTime.now());
        projetOngRepository.persist(testProjet);
    }

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

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

    @Test
    @TestSecurity(user = "admin@unionflow.com", roles = { "ADMIN", "ADMIN_ORGANISATION", "ONG_RESP" })
    @DisplayName("GET /api/v1/ong/projets/{id} existant retourne 200")
    void getProjetById_existant_returns200() {
        given()
                .pathParam("id", testProjet.getId())
                .when()
                .get("/api/v1/ong/projets/{id}")
                .then()
                .statusCode(200)
                .body("id", notNullValue());
    }

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

    @Test
    @TestSecurity(user = "admin@unionflow.com", roles = { "ADMIN", "ADMIN_ORGANISATION", "ONG_RESP" })
    @DisplayName("POST creerProjet avec organisation valide retourne 201")
    void creerProjet_valid_returns201() {
        String body = "{"
                + "\"organisationId\": \"" + testOrganisation.getId() + "\","
                + "\"nomProjet\": \"Projet POST Test\""
                + "}";
        String projetId = given()
                .contentType(ContentType.JSON)
                .body(body)
                .when()
                .post("/api/v1/ong/projets")
                .then()
                .statusCode(201)
                .body("id", notNullValue())
                .extract().path("id");

        if (projetId != null) {
            try {
                cleanupProjet(UUID.fromString(projetId));
            } catch (Exception e) {
                // best effort
            }
        }
    }

    @Transactional
    void cleanupProjet(UUID id) {
        projetOngRepository.deleteById(id);
    }

    @Test
    @TestSecurity(user = "admin@unionflow.com", roles = { "ADMIN", "ADMIN_ORGANISATION", "ONG_RESP" })
    @DisplayName("PATCH changerStatut sans query param statut retourne 400")
    void changerStatut_sansStatut_returns400() {
        given()
                .pathParam("id", UUID.randomUUID())
                .when()
                .patch("/api/v1/ong/projets/{id}/statut")
                .then()
                .statusCode(400);
    }

    @Test
    @TestSecurity(user = "admin@unionflow.com", roles = { "ADMIN", "ADMIN_ORGANISATION", "ONG_RESP" })
    @DisplayName("PATCH changerStatut avec statut valide et ID inexistant retourne 404")
    void changerStatut_avecStatutValidEtIdInexistant_returns404() {
        given()
                .pathParam("id", UUID.randomUUID())
                .queryParam("statut", "EN_COURS")
                .when()
                .patch("/api/v1/ong/projets/{id}/statut")
                .then()
                .statusCode(404);
    }

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

    @Test
    @TestSecurity(user = "admin@unionflow.com", roles = { "ADMIN", "ADMIN_ORGANISATION", "ONG_RESP" })
    @DisplayName("PATCH changerStatut avec statut valide et ID existant retourne 200")
    void changerStatut_avecStatutValidEtIdExistant_returns200() {
        given()
                .pathParam("id", testProjet.getId())
                .queryParam("statut", "EN_COURS")
                .when()
                .patch("/api/v1/ong/projets/{id}/statut")
                .then()
                .statusCode(200)
                .body("id", notNullValue());
    }
}
