<?php

namespace App\Patient\Repository;

use App\Patient\Entity\PatientCall;
use App\Patient\Entity\PatientRecord;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;

class PatientCallRepository extends ServiceEntityRepository
{
    public function __construct(ManagerRegistry $registry)
    {
        parent::__construct($registry, PatientCall::class);
    }

    public function findByUuid(string $uuid): ?PatientCall
    {
        return $this->findOneBy(['uuid' => $uuid]);
    }

    /**
     * Newest-first call log for a record, optionally filtered by outcome.
     *
     * @return PatientCall[]
     */
    public function findByRecord(PatientRecord $record, ?string $outcome = null): array
    {
        $qb = $this->createQueryBuilder('c')
            ->where('c.record = :record')
            ->setParameter('record', $record)
            ->orderBy('c.calledAt', 'DESC')
            ->addOrderBy('c.id', 'DESC');

        if ($outcome !== null) {
            $qb->andWhere('c.outcome = :outcome')->setParameter('outcome', $outcome);
        }

        return $qb->getQuery()->getResult();
    }

    public function save(PatientCall $c): void
    {
        $this->getEntityManager()->persist($c);
        $this->getEntityManager()->flush();
    }

    public function remove(PatientCall $c): void
    {
        $this->getEntityManager()->remove($c);
        $this->getEntityManager()->flush();
    }
}
