<?php

declare(strict_types=1);

/*
 * Chill is a software for social workers
 *
 * For the full copyright and license information, please view
 * the LICENSE file that was distributed with this source code.
 */

namespace Chill\TicketBundle\Repository;

use Chill\PersonBundle\Entity\Person;
use Chill\TicketBundle\Entity\Ticket;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\Persistence\ObjectRepository;

final readonly class TicketRepository implements TicketRepositoryInterface
{
    private ObjectRepository $repository;

    public function __construct(private EntityManagerInterface $objectManager)
    {
        $this->repository = $objectManager->getRepository($this->getClassName());
    }

    public function find($id): ?Ticket
    {
        return $this->repository->find($id);
    }

    public function findAll(): array
    {
        return $this->repository->findAll();
    }

    /**
     * @return list<Ticket>
     */
    public function findAllOrdered(): array
    {
        return $this->objectManager->createQuery('SELECT t FROM '.$this->getClassName().' t ORDER BY t.id DESC')->getResult();
    }

    public function findBy(array $criteria, ?array $orderBy = null, ?int $limit = null, ?int $offset = null): array
    {
        return $this->repository->findBy($criteria, $orderBy, $limit, $offset);
    }

    public function findOneBy(array $criteria): ?Ticket
    {
        return $this->repository->findOneBy($criteria);
    }

    public function getClassName()
    {
        return Ticket::class;
    }

    public function findOneByExternalRef(string $extId): ?Ticket
    {
        return $this->repository->findOneBy(['externalRef' => $extId]);
    }

    /**
     * Count tickets associated with a person where endDate is null.
     */
    public function countOpenedByPerson(Person $person): int
    {
        return (int) $this->objectManager->createQuery(
            'SELECT COUNT(DISTINCT t.id) FROM '.$this->getClassName().' t
             JOIN t.personHistories ph
             WHERE ph.person = :person
             AND ph.endDate IS NULL'
        )
            ->setParameter('person', $person)
            ->getSingleScalarResult();
    }
}
