<?php

declare(strict_types=1);

namespace App\Doctrine\Organization;

use ApiPlatform\Metadata\Operation;
use App\Doctrine\AbstractExtension;
use App\Entity\Access\Access;
use App\Entity\Organization\Organization;
use App\Entity\Organization\OrganizationAddressPostal;
use App\Entity\Organization\OrganizationArticle;
use App\Entity\Organization\Subdomain;
use Doctrine\ORM\QueryBuilder;
use Symfony\Bundle\SecurityBundle\Security;

/**
 * Class CurrentOrganizationExtension : Filtre de sécurité par défaut pour une resource Organization.
 */
final class CurrentParentOrganizationExtension extends AbstractExtension
{
    public function __construct(private Security $security)
    {
    }

    public function supports(string $resourceClass, ?Operation $operation): bool
    {
        return in_array($resourceClass, [OrganizationAddressPostal::class, OrganizationArticle::class, Subdomain::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.organization = :organization', $rootAlias))
            ->setParameter('organization', $currentUser->getOrganization()->getId())
        ;
    }
}
