<?php
declare(strict_types=1);

namespace App\Doctrine\Core;

use App\Doctrine\AbstractExtension;
use App\Entity\Access\Access;
use App\Entity\Core\Notification;
use Doctrine\ORM\QueryBuilder;
use Symfony\Bundle\SecurityBundle\Security;

/**
 * Class NotificationExtension : Filtre de sécurité par défaut pour une resource Notification
 * @package App\Doctrine\Core
 */
final class CurrentUserNotificationExtension 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 (Notification::class !== $resourceClass) {
            return;
        }

        /** @var Access $currentUser */
        $currentUser = $this->security->getUser();
        $rootAlias = $queryBuilder->getRootAliases()[0];
        $queryBuilder
            ->andWhere(sprintf('%s.discr = :discr', $rootAlias))
            ->andWhere(sprintf('%s.recipientAccess = :current_access', $rootAlias))
            ->andWhere('o.availabilityDate IS NULL or o.availabilityDate <= :today')
            ->setParameter('discr', 'notification')
            ->setParameter('current_access', $currentUser)
            ->setParameter('today', new \DateTime())
        ;
    }
}