<?php
declare(strict_types=1);

namespace App\Doctrine\Access;

use App\Doctrine\AbstractExtension;
use App\Entity\Access\Access;
use App\Service\ServiceIterator\CurrentAccessExtensionIterator;
use Doctrine\ORM\QueryBuilder;
use Symfony\Component\Security\Core\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
    )
    { }

    protected function addWhere(QueryBuilder $queryBuilder, string $resourceClass, string $operationName): void
    {
        if (Access::class !== $resourceClass) {
            return;
        }

        /** @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, $operationName);
    }
}
