<?php

declare(strict_types=1);

namespace App\Repository;

use App\Entity\Employee;
use App\Entity\Formation;
use App\Repository\Contract\FormationReadRepositoryInterface;
use DateTimeImmutable;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;

/**
 * @extends ServiceEntityRepository<Formation>
 */
final class FormationRepository extends ServiceEntityRepository implements FormationReadRepositoryInterface
{
    public function __construct(ManagerRegistry $registry)
    {
        parent::__construct($registry, Formation::class);
    }

    /**
     * @param list<Employee> $employees
     *
     * @return list<Formation>
     */
    public function findByDateAndEmployees(DateTimeImmutable $date, array $employees): array
    {
        if ([] === $employees) {
            return [];
        }

        $qb = $this->createQueryBuilder('f')
            ->leftJoin('f.employee', 'e')
            ->addSelect('e')
            ->andWhere('f.startDate <= :date')
            ->andWhere('f.endDate >= :date')
            ->andWhere('f.employee IN (:employees)')
            ->setParameter('date', $date)
            ->setParameter('employees', $employees)
        ;

        // @var list<Formation>
        return $qb->getQuery()->getResult();
    }

    /**
     * @param list<Employee> $employees
     *
     * @return list<Formation>
     */
    public function findByDateRangeAndEmployees(DateTimeImmutable $from, DateTimeImmutable $to, array $employees): array
    {
        if ([] === $employees) {
            return [];
        }

        $qb = $this->createQueryBuilder('f')
            ->leftJoin('f.employee', 'e')
            ->addSelect('e')
            ->andWhere('f.startDate <= :to')
            ->andWhere('f.endDate >= :from')
            ->andWhere('f.employee IN (:employees)')
            ->setParameter('from', $from)
            ->setParameter('to', $to)
            ->setParameter('employees', $employees)
        ;

        // @var list<Formation>
        return $qb->getQuery()->getResult();
    }
}
