<?php

declare(strict_types=1);

namespace App\Doctrine\Access;

use ApiPlatform\Metadata\Operation;
use App\Doctrine\AbstractExtension;
use App\Entity\Access\PersonalizedList;
use Doctrine\ORM\QueryBuilder;
use Symfony\Bundle\SecurityBundle\Security;

/**
 * Class CurrentUserPersonalizedListExtension : Filtre de sécurité par défaut pour une resource PersonalizedList.
 */
final class CurrentUserPersonalizedListExtension extends AbstractExtension
{
    public function __construct(private Security $security)
    {
    }

    public function supports(string $resourceClass, ?Operation $operation): bool
    {
        return $resourceClass === PersonalizedList::class;
    }

    protected function addWhere(QueryBuilder $queryBuilder, string $resourceClass, ?Operation $operation): void
    {
        $currentUser = $this->security->getUser();
        $rootAliases = $queryBuilder->getRootAliases();
        if (empty($rootAliases)) {
            throw new \LogicException('No root alias defined.');
        }
        $rootAlias = $rootAliases[0];
        $queryBuilder->andWhere(sprintf('%s.access = :current_access', $rootAlias));
        $queryBuilder->setParameter('current_access', $currentUser);
    }
}
