package dev.lions.unionflow.server.repository;

import dev.lions.unionflow.server.entity.DonRecu;
import io.quarkus.hibernate.orm.panache.PanacheRepositoryBase;
import jakarta.enterprise.context.ApplicationScoped;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.List;
import java.util.UUID;

/** Repository des dons reçus (numéraire / nature / bénévolat / legs). */
@ApplicationScoped
public class DonRecuRepository implements PanacheRepositoryBase<DonRecu, UUID> {

  public List<DonRecu> findByOrganisation(UUID organisationId) {
    return list("organisationId = ?1 ORDER BY dateDon DESC", organisationId);
  }

  public List<DonRecu> findByDonateur(UUID donateurId) {
    return list("donateur.id = ?1 ORDER BY dateDon DESC", donateurId);
  }

  public List<DonRecu> findEntre(UUID organisationId, LocalDate from, LocalDate to) {
    return list("organisationId = ?1 AND dateDon BETWEEN ?2 AND ?3 ORDER BY dateDon DESC",
        organisationId, from, to);
  }

  /** Total des dons reçus par organisation et période (pour reporting AIRMS / SYCEBNL). */
  public BigDecimal totalEntre(UUID organisationId, LocalDate from, LocalDate to) {
    Object result = getEntityManager()
        .createQuery(
            "SELECT COALESCE(SUM(COALESCE(d.montantXof, d.valorisationXof, 0)), 0) "
                + "FROM DonRecu d "
                + "WHERE d.organisationId = :org "
                + "AND d.dateDon BETWEEN :from AND :to "
                + "AND d.actif = true")
        .setParameter("org", organisationId)
        .setParameter("from", from)
        .setParameter("to", to)
        .getSingleResult();
    return result instanceof BigDecimal bd ? bd : BigDecimal.ZERO;
  }
}
