<?php

declare(strict_types=1);

namespace App\Doctrine\Access;

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.
 */
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;
    }

    protected function addWhere(QueryBuilder $queryBuilder, string $resourceClass, ?Operation $operation): void
    {
        $token = $this->security->getToken();
        if ($token === null) {
            return;
        }
        $currentUser = $token->getUser();
        if (!$currentUser instanceof Access) {
            return;
        }
        $organization = $currentUser->getOrganization();
        $rootAliases = $queryBuilder->getRootAliases();
        if (empty($rootAliases)) {
            throw new \LogicException('No root alias defined.');
        }

        $rootAlias = $rootAliases[0];
        $queryBuilder->andWhere(sprintf('%s.organization = :current_organization', $rootAlias));
        $queryBuilder->setParameter('current_organization', $organization);

        $operationName = $operation ? $operation->getName() : '';
        $this->currentAccessExtensionIterator->addWhere($queryBuilder, $operationName);
    }
}
