package dev.lions.unionflow.server.repository;

import dev.lions.unionflow.server.entity.DemandeAdhesion;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.persistence.TypedQuery;
import java.util.List;
import java.util.Optional;
import java.util.UUID;

/**
 * Repository pour l'entité DemandeAdhesion
 *
 * @author UnionFlow Team
 * @version 2.0
 * @since 2025-02-18
 */
@ApplicationScoped
public class AdhesionRepository extends BaseRepository<DemandeAdhesion> {

  public AdhesionRepository() {
    super(DemandeAdhesion.class);
  }

  public Optional<DemandeAdhesion> findByNumeroReference(String numeroReference) {
    TypedQuery<DemandeAdhesion> query = entityManager.createQuery(
        "SELECT a FROM DemandeAdhesion a WHERE a.numeroReference = :numeroReference",
        DemandeAdhesion.class);
    query.setParameter("numeroReference", numeroReference);
    return query.getResultList().stream().findFirst();
  }

  public List<DemandeAdhesion> findByMembreId(UUID membreId) {
    TypedQuery<DemandeAdhesion> query = entityManager.createQuery(
        "SELECT a FROM DemandeAdhesion a WHERE a.utilisateur.id = :membreId",
        DemandeAdhesion.class);
    query.setParameter("membreId", membreId);
    return query.getResultList();
  }

  public List<DemandeAdhesion> findByOrganisationId(UUID organisationId) {
    TypedQuery<DemandeAdhesion> query = entityManager.createQuery(
        "SELECT a FROM DemandeAdhesion a WHERE a.organisation.id = :organisationId",
        DemandeAdhesion.class);
    query.setParameter("organisationId", organisationId);
    return query.getResultList();
  }

  public List<DemandeAdhesion> findByStatut(String statut) {
    TypedQuery<DemandeAdhesion> query = entityManager.createQuery(
        "SELECT a FROM DemandeAdhesion a WHERE a.statut = :statut", DemandeAdhesion.class);
    query.setParameter("statut", statut);
    return query.getResultList();
  }

  public List<DemandeAdhesion> findEnAttente() {
    return findByStatut("EN_ATTENTE");
  }

  public List<DemandeAdhesion> findApprouveesEnAttentePaiement() {
    TypedQuery<DemandeAdhesion> query = entityManager.createQuery(
        "SELECT a FROM DemandeAdhesion a WHERE a.statut = :statut"
            + " AND (a.montantPaye IS NULL OR a.montantPaye < a.fraisAdhesion)",
        DemandeAdhesion.class);
    query.setParameter("statut", "APPROUVEE");
    return query.getResultList();
  }
}
