<?php

declare(strict_types=1);

namespace App\Doctrine;

use ApiPlatform\Doctrine\Orm\Extension\QueryCollectionExtensionInterface;
use ApiPlatform\Doctrine\Orm\Util\QueryNameGeneratorInterface;
use ApiPlatform\Metadata\Operation;
use App\Entity\User;
use App\Entity\WorkHour;
use App\Security\EmployeeScopeService;
use Doctrine\ORM\QueryBuilder;
use Symfony\Bundle\SecurityBundle\Security;

final readonly class WorkHourCollectionExtension implements QueryCollectionExtensionInterface
{
    public function __construct(
        private Security $security,
        private EmployeeScopeService $employeeScopeService,
    ) {}

    public function applyToCollection(
        QueryBuilder $queryBuilder,
        QueryNameGeneratorInterface $queryNameGenerator,
        string $resourceClass,
        ?Operation $operation = null,
        array $context = []
    ): void {
        // N'applique le filtrage qu'à la ressource WorkHour.
        if (WorkHour::class !== $resourceClass) {
            return;
        }

        $user = $this->security->getUser();
        if (!$user instanceof User) {
            // Pas d'utilisateur => aucune ligne renvoyée.
            $queryBuilder->andWhere('1 = 0');

            return;
        }

        $rootAlias     = $queryBuilder->getRootAliases()[0];
        $employeeAlias = 'employee_scope';

        $queryBuilder->leftJoin(sprintf('%s.employee', $rootAlias), $employeeAlias)
            ->addSelect($employeeAlias)
        ;

        // Filtrage SQL par scope (admin/self/site) avant retour API.
        $this->employeeScopeService->applyEmployeeScope($queryBuilder, $employeeAlias, 'work_hour_scope', $user);
    }
}
