<?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\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  implements QueryCollectionExtensionInterface, QueryItemExtensionInterface
{
    public function __construct(
        private Security $security,
        private CurrentAccessExtensionIterator $currentAccessExtensionIterator
    )
    { }

    /**
     * @param QueryBuilder $queryBuilder
     * @param QueryNameGeneratorInterface $queryNameGenerator
     * @param string $resourceClass
     * @param Operation|null $operation
     * @param mixed[] $context
     * @return void
     */
    public function applyToCollection(QueryBuilder $queryBuilder, QueryNameGeneratorInterface $queryNameGenerator, string $resourceClass, Operation $operation = null, array $context = []): void
    {
        $this->addWhere($queryBuilder, $resourceClass, $operation?->getName());
    }

    /**
     * @param QueryBuilder $queryBuilder
     * @param QueryNameGeneratorInterface $queryNameGenerator
     * @param string $resourceClass
     * @param list<int> $identifiers
     * @param Operation|null $operation
     * @param mixed[] $context
     * @return void
     */
    public function applyToItem(QueryBuilder $queryBuilder, QueryNameGeneratorInterface $queryNameGenerator, string $resourceClass, array $identifiers, Operation $operation = null, array $context = []): void
    {
        $this->addWhere($queryBuilder, $resourceClass, $operation?->getName());
    }

    public 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);
    }
}
