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

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

import dev.lions.unionflow.server.api.enums.vote.ModeScrutin;
import dev.lions.unionflow.server.api.enums.vote.StatutVote;
import dev.lions.unionflow.server.api.enums.vote.TypeVote;
import dev.lions.unionflow.server.entity.Organisation;
import dev.lions.unionflow.server.entity.vote.CampagneVote;
import dev.lions.unionflow.server.repository.OrganisationRepository;
import dev.lions.unionflow.server.repository.vote.CampagneVoteRepository;
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 CampagneVoteResourceTest {

    @Inject
    OrganisationRepository organisationRepository;

    @Inject
    CampagneVoteRepository campagneVoteRepository;

    private Organisation testOrganisation;
    private CampagneVote testCampagne;

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

        testCampagne = CampagneVote.builder()
                .titre("Campagne Vote Test Resource")
                .organisation(testOrganisation)
                .typeVote(TypeVote.ELECTION_BUREAU)
                .modeScrutin(ModeScrutin.MAJORITAIRE_UN_TOUR)
                .statut(StatutVote.BROUILLON)
                .dateOuverture(LocalDateTime.now().plusDays(1))
                .dateFermeture(LocalDateTime.now().plusDays(7))
                .build();
        testCampagne.setActif(true);
        testCampagne.setDateCreation(LocalDateTime.now());
        campagneVoteRepository.persist(testCampagne);
    }

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

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

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

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

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

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

    @Test
    @TestSecurity(user = "admin@unionflow.com", roles = { "ADMIN", "ADMIN_ORGANISATION", "VOTE_RESP" })
    @DisplayName("POST creerCampagne avec organisation valide retourne 201")
    void creerCampagne_valid_returns201() {
        String body = "{"
                + "\"titre\": \"Campagne POST Test\","
                + "\"organisationId\": \"" + testOrganisation.getId() + "\","
                + "\"typeVote\": \"ELECTION_BUREAU\","
                + "\"modeScrutin\": \"MAJORITAIRE_UN_TOUR\","
                + "\"dateOuverture\": \"" + LocalDateTime.now().plusDays(2).toString() + "\","
                + "\"dateFermeture\": \"" + LocalDateTime.now().plusDays(10).toString() + "\""
                + "}";
        String campagneId = given()
                .contentType(ContentType.JSON)
                .body(body)
                .when()
                .post("/api/v1/vote/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) {
        campagneVoteRepository.deleteById(id);
    }

    @Test
    @TestSecurity(user = "admin@unionflow.com", roles = { "ADMIN", "ADMIN_ORGANISATION", "VOTE_RESP" })
    @DisplayName("POST ajouterCandidat avec campagne valide retourne 201")
    void ajouterCandidat_campagneValide_returns201() {
        String body = "{"
                + "\"nomCandidatureOuChoix\": \"Candidat Test\""
                + "}";
        given()
                .contentType(ContentType.JSON)
                .body(body)
                .pathParam("id", testCampagne.getId())
                .when()
                .post("/api/v1/vote/campagnes/{id}/candidats")
                .then()
                .statusCode(201)
                .body("id", notNullValue());
    }

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

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

    @Test
    @TestSecurity(user = "admin@unionflow.com", roles = { "ADMIN", "ADMIN_ORGANISATION", "VOTE_RESP" })
    @DisplayName("POST ajouterCandidat avec ID inexistant retourne 4xx")
    void ajouterCandidat_idInexistant_returns4xx() {
        given()
                .contentType(ContentType.JSON)
                .body("{}")
                .pathParam("id", UUID.randomUUID())
                .when()
                .post("/api/v1/vote/campagnes/{id}/candidats")
                .then()
                .statusCode(anyOf(equalTo(400), equalTo(404), equalTo(500)));
    }
}
