<?php

namespace Myvetshop\Module\Clinique\Repository;

use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\ORM\QueryBuilder;
use Doctrine\Persistence\ManagerRegistry;
use Myvetshop\Module\Clinique\Entity\EstablishmentEvent;
use Myvetshop\Module\Clinique\Entity\MyvetshopClinique;

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

    public function createByCliniqueQueryBuild(MyvetshopClinique $clinique): QueryBuilder
    {
        return $this->createQueryBuilder('event')
        ->where('event.clinique = :clinique')
        ->setParameter('clinique', $clinique);
    }

    public function getLastEventIdByClinique(MyvetshopClinique $clinique): ?int
    {
        $ret = $this->createByCliniqueQueryBuild($clinique)
            ->select('MAX(event.id)')
            ->getQuery()
            ->getSingleScalarResult();

        \assert(null === $ret || \is_int($ret));

        return $ret;
    }

    /**
     * @return list<EstablishmentEvent>
     */
    public function findEventsByClinique(
        MyvetshopClinique $clinique,
        int $after,
        int $limit
    ): array {
        /** @var EstablishmentEvent[] $events */
        $events = $this->createByCliniqueQueryBuild($clinique)
            ->select('event')
            ->andWhere('event.id > :after')
            ->orderBy('event.id', 'ASC')
            ->setParameter('after', $after)
            ->setMaxResults($limit)
            ->getQuery()
            ->getResult();

        return $events;
    }
}
