<?php

namespace App\Cancellation\Repository;

use App\Appointment\Entity\Appointment;
use App\Cancellation\Entity\NoShowRecord;
use App\Patient\Entity\PatientRecord;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;

/** @extends ServiceEntityRepository<NoShowRecord> */
class NoShowRecordRepository extends ServiceEntityRepository
{
    /** پنجرهٔ شمارش — عدم حضورِ سه سال پیش امروز معنایی ندارد. */
    public const WINDOW_DAYS = 365;

    public function __construct(ManagerRegistry $registry)
    {
        parent::__construct($registry, NoShowRecord::class);
    }

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

    public function countRecent(PatientRecord $patient, ?int $now = null): int
    {
        $since = ($now ?? time()) - self::WINDOW_DAYS * 86400;

        return (int) $this->createQueryBuilder('r')
            ->select('COUNT(r.id)')
            ->where('r.patientRecord = :patient')
            ->andWhere('r.recordedAt >= :since')
            ->setParameter('patient', $patient)
            ->setParameter('since', $since)
            ->getQuery()
            ->getSingleScalarResult();
    }

    /** @return NoShowRecord[] */
    public function historyFor(PatientRecord $patient, int $limit = 20): array
    {
        return $this->createQueryBuilder('r')
            ->where('r.patientRecord = :patient')
            ->setParameter('patient', $patient)
            ->orderBy('r.recordedAt', 'DESC')
            ->setMaxResults($limit)
            ->getQuery()
            ->getResult();
    }
}
