<?php
declare(strict_types=1);

namespace App\Doctrine\Access;

use ApiPlatform\Doctrine\Orm\Extension\QueryCollectionExtensionInterface;
use ApiPlatform\Doctrine\Orm\Extension\QueryItemExtensionInterface;
use ApiPlatform\Doctrine\Orm\Util\QueryNameGeneratorInterface;
use ApiPlatform\Metadata\Operation;
use App\Doctrine\AbstractExtension;
use App\Entity\Access\Access;
use App\Service\ServiceIterator\CurrentAccessExtensionIterator;
use Doctrine\ORM\QueryBuilder;
use Symfony\Bundle\SecurityBundle\Security;

/**
 * Class CurrentAccessExtension : Filtre de sécurité par défaut pour une resource Access
 * @package App\Doctrine\Access
 */
final class CurrentAccessExtension extends AbstractExtension
{
    public function __construct(
        private Security $security,
        private CurrentAccessExtensionIterator $currentAccessExtensionIterator
    )
    { }

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

    public function addWhere(QueryBuilder $queryBuilder, string $resourceClass, ?Operation $operation): void
    {
        /** @var Access $currentUser */
        $currentUser = $this->security->getUser();
        $rootAlias = $queryBuilder->getRootAliases()[0];
        $queryBuilder
            ->andWhere(sprintf('%s.organization = :current_organization', $rootAlias))
            ->setParameter('current_organization', $currentUser->getOrganization())
        ;

        $this->currentAccessExtensionIterator->addWhere($queryBuilder, $operation?->getName());
    }
}
