<?php
declare(strict_types=1);

namespace App\Doctrine\Billing;

use App\Doctrine\AbstractExtension;
use App\Entity\Access\Access;
use App\Entity\Billing\ResidenceArea;
use Doctrine\ORM\QueryBuilder;
use Symfony\Bundle\SecurityBundle\Security;

/**
 * Class CurrentResidenceAreaExtension : Filtre de sécurité par défaut pour une resource ResidenceArea
 * @package App\Doctrine\Core
 */
final class CurrentResidenceAreaExtension extends AbstractExtension
{
    public function __construct(private Security $security)
    { }

    protected function addWhere(QueryBuilder $queryBuilder, string $resourceClass): void
    {
        if (ResidenceArea::class !== $resourceClass) {
            return;
        }

        /** @var Access $currentUser */
        $currentUser = $this->security->getUser();
        $rootAlias = $queryBuilder->getRootAliases()[0];
        $queryBuilder
            ->andWhere(sprintf('%s.billingSetting = :billingSetting', $rootAlias))
            ->setParameter('billingSetting', $currentUser->getOrganization()->getBillingSetting())
        ;
    }
}