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

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

import dev.lions.unionflow.server.entity.Organisation;
import dev.lions.unionflow.server.entity.culte.DonReligieux;
import dev.lions.unionflow.server.repository.OrganisationRepository;
import dev.lions.unionflow.server.repository.culte.DonReligieuxRepository;
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.math.BigDecimal;
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 DonReligieuxResourceTest {

    @Inject
    OrganisationRepository organisationRepository;

    @Inject
    DonReligieuxRepository donReligieuxRepository;

    private Organisation testOrganisation;
    private DonReligieux testDon;

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

        testDon = DonReligieux.builder()
                .institution(testOrganisation)
                .typeDon(dev.lions.unionflow.server.api.enums.culte.TypeDonReligieux.QUETE_ORDINAIRE)
                .montant(BigDecimal.valueOf(5000))
                .dateEncaissement(LocalDateTime.now())
                .build();
        testDon.setActif(true);
        testDon.setDateCreation(LocalDateTime.now());
        donReligieuxRepository.persist(testDon);
    }

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

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

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

    @Test
    @TestSecurity(user = "admin@unionflow.com", roles = { "ADMIN", "ADMIN_ORGANISATION", "CULTE_RESP" })
    @DisplayName("GET /api/v1/culte/dons/organisation/{id} retourne 200 ou 500")
    void getDonsByOrganisation_returns200ou500() {
        given()
                .pathParam("organisationId", UUID.randomUUID())
                .when()
                .get("/api/v1/culte/dons/organisation/{organisationId}")
                .then()
                .statusCode(anyOf(equalTo(200), equalTo(500)))
                .body("$", notNullValue());
    }

    @Test
    @TestSecurity(user = "admin@unionflow.com", roles = { "ADMIN", "ADMIN_ORGANISATION", "MEMBRE" })
    @DisplayName("POST enregistrerDon avec institution valide retourne 201")
    void enregistrerDon_valid_returns201() {
        String body = "{"
                + "\"institutionId\": \"" + testOrganisation.getId() + "\","
                + "\"typeDon\": \"QUETE_ORDINAIRE\","
                + "\"montant\": 2500"
                + "}";
        String donId = given()
                .contentType(ContentType.JSON)
                .body(body)
                .when()
                .post("/api/v1/culte/dons")
                .then()
                .statusCode(201)
                .body("id", notNullValue())
                .extract().path("id");

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

    @Transactional
    void cleanupDon(UUID id) {
        donReligieuxRepository.deleteById(id);
    }

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