<?php

declare(strict_types=1);

namespace App\Repository;

use App\Entity\Employee;
use App\Entity\EmployeeRttPayment;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;

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

    public function findOneByEmployeeYearMonth(Employee $employee, int $year, int $month): ?EmployeeRttPayment
    {
        return $this->findOneBy([
            'employee' => $employee,
            'year'     => $year,
            'month'    => $month,
        ]);
    }

    /**
     * @return EmployeeRttPayment[]
     */
    public function findByEmployeeAndYear(Employee $employee, int $year): array
    {
        return $this->createQueryBuilder('p')
            ->andWhere('p.employee = :employee')
            ->andWhere('p.year = :year')
            ->setParameter('employee', $employee)
            ->setParameter('year', $year)
            ->addOrderBy('p.month', 'ASC')
            ->getQuery()
            ->getResult()
        ;
    }

    /**
     * @return EmployeeRttPayment[]
     */
    public function findByYearAndMonth(int $year, int $month): array
    {
        return $this->createQueryBuilder('p')
            ->andWhere('p.year = :year')
            ->andWhere('p.month = :month')
            ->setParameter('year', $year)
            ->setParameter('month', $month)
            ->innerJoin('p.employee', 'e')
            ->addSelect('e')
            ->getQuery()
            ->getResult()
        ;
    }

    /**
     * Paiements de plusieurs employés sur plusieurs exercices (fetch groupé,
     * évite le N+1 sur l'export PDF). Jointure employé chargée.
     *
     * @param list<Employee> $employees
     * @param list<int>      $years     années d'exercice
     *
     * @return EmployeeRttPayment[]
     */
    public function findByEmployeesAndYears(array $employees, array $years): array
    {
        if ([] === $employees || [] === $years) {
            return [];
        }

        return $this->createQueryBuilder('p')
            ->andWhere('p.employee IN (:employees)')
            ->andWhere('p.year IN (:years)')
            ->setParameter('employees', $employees)
            ->setParameter('years', $years)
            ->innerJoin('p.employee', 'e')
            ->addSelect('e')
            ->getQuery()
            ->getResult()
        ;
    }
}
