import { PrismaClient } from '@prisma/client';

const prisma = new PrismaClient();

export async function getDashboardKPIs(anneeScolaireId?: number) {
  let yearFilter = anneeScolaireId;
  if (!yearFilter) {
    const activeYear = await prisma.anneeScolaire.findFirst({ where: { isActive: true } });
    yearFilter = activeYear?.id;
  }

  const whereYear = yearFilter ? { anneeScolaireId: yearFilter } : {};

  const totalEtudiants = await prisma.etudiant.count({
    where: { ...whereYear, statut: { in: ['ACTIF', 'SUSPENDU'] } },
  });

  const paiements = await prisma.paiement.findMany({
    where: { etudiant: whereYear },
  });
  const caRealise = paiements.reduce((sum, p) => sum + p.montant, 0);

  const echeancesImpayees = await prisma.echeanceMensuelle.findMany({
    where: {
      statut: 'EN_RETARD',
      echeancier: whereYear,
    },
  });
  const impayes = echeancesImpayees.reduce((sum, e) => sum + (e.montantDu - e.montantPaye), 0);

  const totalDu = await prisma.echeancier.aggregate({
    where: whereYear,
    _sum: { montantTotal: true },
  });
  const tauxRecouvrement = totalDu._sum.montantTotal
    ? Math.round((caRealise / totalDu._sum.montantTotal) * 100)
    : 0;

  return { totalEtudiants, caRealise, tauxRecouvrement, impayes };
}
