<?php

declare(strict_types=1);

namespace App\Doctrine\Core;

use ApiPlatform\Metadata\Operation;
use App\Doctrine\AbstractExtension;
use App\Entity\Access\Access;
use App\Entity\Core\AddressPostal;
use Doctrine\ORM\QueryBuilder;
use Symfony\Bundle\SecurityBundle\Security;

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

    public function supports(string $resourceClass, ?Operation $operation): bool
    {
        return $resourceClass === AddressPostal::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;
        }

        $rootAliases = $queryBuilder->getRootAliases();
        if (empty($rootAliases)) {
            throw new \LogicException('No root alias defined.');
        }

        $rootAlias = $rootAliases[0];
        $queryBuilder
            ->innerJoin(sprintf('%s.organizationAddressPostal', $rootAlias), 'organization_address_postal')
            ->andWhere('organization_address_postal.organization = :organization')
            ->setParameter('organization', $currentUser->getOrganization());
    }
}
