<?php

namespace App\Course\Repository;

use App\ClinicService\Entity\ServiceItem;
use App\Course\Entity\TreatmentCourse;
use App\Patient\Entity\PatientRecord;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;

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

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

    public function findActiveFor(PatientRecord $patient, ServiceItem $service): ?TreatmentCourse
    {
        return $this->findOneBy([
            'patientRecord' => $patient,
            'serviceItem'   => $service,
            'status'        => TreatmentCourse::STATUS_ACTIVE,
        ]);
    }

    /** @return TreatmentCourse[] */
    public function findForPatient(PatientRecord $patient): array
    {
        return $this->createQueryBuilder('c')
            ->addSelect('s')
            ->leftJoin('c.sessions', 's')
            ->where('c.patientRecord = :patient')
            ->setParameter('patient', $patient)
            ->orderBy('c.startedAt', 'DESC')
            ->getQuery()
            ->getResult();
    }

    public function save(TreatmentCourse $course, bool $flush = true): void
    {
        $this->getEntityManager()->persist($course);

        if ($flush) {
            $this->getEntityManager()->flush();
        }
    }
}
