<?php

declare(strict_types=1);

namespace App\Repository;

use App\Entity\EcheancePaiement;
use App\Entity\LignePaiement;
use App\Entity\Paiement;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;

/** @extends ServiceEntityRepository<LignePaiement> */
final class LignePaiementRepository extends ServiceEntityRepository
{
    public function __construct(ManagerRegistry $registry)
    {
        parent::__construct($registry, LignePaiement::class);
    }

    public function sumPaidByEcheance(EcheancePaiement $echeance): float
    {
        return (float) ($this->createQueryBuilder('l')
            ->select('COALESCE(SUM(l.montant), 0)')
            ->join('l.paiement', 'p')
            ->andWhere('l.echeancePaiement = :echeance')
            ->andWhere('p.statut = :statut')
            ->setParameter('echeance', $echeance)
            ->setParameter('statut', Paiement::STATUT_VALIDE)
            ->getQuery()
            ->getSingleScalarResult() ?? 0);
    }
}
