<?php

declare(strict_types=1);

namespace App\Repository;

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

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

    public function findOneByEmployeeAndWeek(Employee $employee, DateTimeImmutable $weekStart): ?EmployeeWeekComment
    {
        return $this->findOneBy(['employee' => $employee, 'weekStartDate' => $weekStart]);
    }

    /**
     * @param list<Employee> $employees
     *
     * @return array<int, EmployeeWeekComment> employee_id → comment
     */
    public function findByWeekAndEmployees(DateTimeImmutable $weekStart, array $employees): array
    {
        if ([] === $employees) {
            return [];
        }

        $rows = $this->createQueryBuilder('c')
            ->andWhere('c.weekStartDate = :weekStart')
            ->andWhere('c.employee IN (:employees)')
            ->setParameter('weekStart', $weekStart)
            ->setParameter('employees', $employees)
            ->innerJoin('c.employee', 'e')->addSelect('e')
            ->getQuery()->getResult()
        ;

        $map = [];
        foreach ($rows as $row) {
            $eid = $row->getEmployee()?->getId();
            if (null !== $eid) {
                $map[$eid] = $row;
            }
        }

        return $map;
    }
}
