<?php

namespace App\Package\Repository;

use App\Appointment\Entity\Appointment;
use App\Package\Entity\PatientPackage;
use App\Package\Entity\SessionCreditLedger;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;

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

    /** مانده = جمع همهٔ delta ها. هیچ ستون ذخیره‌شده‌ای وجود ندارد. */
    public function sumDelta(PatientPackage $package): int
    {
        return (int) $this->createQueryBuilder('l')
            ->select('COALESCE(SUM(l.delta), 0)')
            ->where('l.patientPackage = :package')
            ->setParameter('package', $package)
            ->getQuery()
            ->getSingleScalarResult();
    }

    /** @return SessionCreditLedger[] قدیمی‌ترین اول — دفتر به ترتیب زمان خوانده می‌شود */
    public function historyFor(PatientPackage $package): array
    {
        return $this->createQueryBuilder('l')
            ->where('l.patientPackage = :package')
            ->setParameter('package', $package)
            ->orderBy('l.createdAt', 'ASC')
            ->addOrderBy('l.id', 'ASC')
            ->getQuery()
            ->getResult();
    }

    public function findForAppointment(Appointment $appointment, string $kind): ?SessionCreditLedger
    {
        return $this->findOneBy(['appointment' => $appointment, 'kind' => $kind]);
    }
}
