<?php

declare(strict_types=1);

namespace App\Doctrine\Custom\Search;

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

/**
 * Filtre de sécurité pour les recherches
 * Restreint les résultats à ceux de l'organization actuelle.
 */
final class RestrictToOrganizationIdExtension extends AbstractExtension
{
    public function __construct(
        private readonly Security $security,
    ) {
    }

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

    protected function addWhere(QueryBuilder $queryBuilder, string $resourceClass, ?Operation $operation): void
    {
        /** @var Access $currentUser */
        $currentUser = $this->security->getUser();
        if ($currentUser === null || $currentUser->getOrganization() === null) {
            return;
        }
        $rootAlias = $queryBuilder->getRootAliases()[0];
        $queryBuilder
            ->andWhere(sprintf('%s.organizationId = :organizationId', $rootAlias))
            ->setParameter('organizationId', $currentUser->getOrganization()->getId())
        ;
    }
}
