<?php
declare(strict_types=1);

namespace App\Doctrine\Booking;

use App\Doctrine\AbstractExtension;
use App\Entity\Access\Access;
use App\Entity\Booking\Course;
use Doctrine\ORM\QueryBuilder;
use Symfony\Bundle\SecurityBundle\Security;

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

    /**
     * @todo : A la suite de la migration, il faut supprimer le where avec le discr.
     */
    protected function addWhere(QueryBuilder $queryBuilder, string $resourceClass): void
    {
        if (Course::class !== $resourceClass) {
            return;
        }

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