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

const prisma = new PrismaClient();

export async function processPayment(etudiantId: number, montant: number) {
  let remainingAmount = montant;

  const echeancier = await prisma.echeancier.findFirst({
    where: { etudiantId },
    include: { echeances: { orderBy: { id: 'asc' } } },
  });

  if (!echeancier) return;

  for (const echeance of echeancier.echeances) {
    if (remainingAmount <= 0) break;
    if (echeance.statut === 'PAYE') continue;

    const due = echeance.montantDu - echeance.montantPaye;
    const payment = Math.min(remainingAmount, due);

    await prisma.echeanceMensuelle.update({
      where: { id: echeance.id },
      data: {
        montantPaye: echeance.montantPaye + payment,
        statut: echeance.montantPaye + payment >= echeance.montantDu ? 'PAYE' : echeance.statut,
        datePaiement: new Date(),
      },
    });

    remainingAmount -= payment;
  }
}
