<?php

namespace App\Course\Repository;

use App\ClinicService\Entity\ServiceItem;
use App\Course\Entity\CourseProtocol;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;

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

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

    public function findForService(ServiceItem $service): ?CourseProtocol
    {
        return $this->findOneBy(['serviceItem' => $service]);
    }

    /** @return CourseProtocol[] */
    public function findForPair(string $entityType, int $entityId): array
    {
        return $this->createQueryBuilder('p')
            ->addSelect('s', 'i')
            ->leftJoin('p.steps', 's')
            ->leftJoin('p.serviceItem', 'i')
            ->where('p.entityType = :type')
            ->andWhere('p.entityId = :id')
            ->setParameter('type', $entityType)
            ->setParameter('id', $entityId)
            ->orderBy('p.createdAt', 'DESC')
            ->getQuery()
            ->getResult();
    }

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

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