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

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

import dev.lions.unionflow.server.api.enums.agricole.StatutCampagneAgricole;
import dev.lions.unionflow.server.entity.Organisation;
import dev.lions.unionflow.server.entity.agricole.CampagneAgricole;
import dev.lions.unionflow.server.repository.OrganisationRepository;
import dev.lions.unionflow.server.repository.agricole.CampagneAgricoleRepository;
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 CampagneAgricoleResourceTest {

    @Inject
    OrganisationRepository organisationRepository;

    @Inject
    CampagneAgricoleRepository campagneAgricoleRepository;

    private Organisation testOrganisation;
    private CampagneAgricole testCampagne;

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

        testCampagne = CampagneAgricole.builder()
                .organisation(testOrganisation)
                .designation("Campagne Agricole Test Resource")
                .statut(StatutCampagneAgricole.PREPARATION)
                .build();
        testCampagne.setActif(true);
        testCampagne.setDateCreation(LocalDateTime.now());
        campagneAgricoleRepository.persist(testCampagne);
    }

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

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

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

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

    @Test
    @TestSecurity(user = "admin@unionflow.com", roles = { "ADMIN", "ADMIN_ORGANISATION", "COOP_RESP" })
    @DisplayName("POST creerCampagne avec cooperative valide retourne 201")
    void creerCampagne_valid_returns201() {
        String body = "{"
                + "\"organisationCoopId\": \"" + testOrganisation.getId() + "\","
                + "\"designation\": \"Campagne POST Test\","
                + "\"statut\": \"PREPARATION\""
                + "}";
        String campagneId = given()
                .contentType(ContentType.JSON)
                .body(body)
                .when()
                .post("/api/v1/agricole/campagnes")
                .then()
                .statusCode(201)
                .body("id", notNullValue())
                .extract().path("id");

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

    @Transactional
    void cleanupCampagne(UUID id) {
        campagneAgricoleRepository.deleteById(id);
    }

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