<?php

namespace App\EventSubscriber;

use App\Entity\User;
use Symfony\Bundle\SecurityBundle\Security;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;

class SuspendedUserSubscriber implements EventSubscriberInterface
{
    public function __construct(
        private Security $security,
        private UrlGeneratorInterface $urlGenerator,
        #[\Symfony\Component\DependencyInjection\Attribute\Autowire('%admin_email%')] private string $adminEmail,
    ) {
    }

    public static function getSubscribedEvents(): array
    {
        return [
            KernelEvents::REQUEST => ['onKernelRequest', 8],
        ];
    }

    private const ALLOWED_ROUTES = ['app_logout', 'app_home', 'app_login'];

    public function onKernelRequest(RequestEvent $event): void
    {
        if (!$event->isMainRequest()) {
            return;
        }

        $user = $this->security->getUser();
        $route = $event->getRequest()->attributes->getString('_route');

        if (!$user instanceof User || !$user->isSuspended() || \in_array($route, self::ALLOWED_ROUTES, true)) {
            return;
        }

        /** @var \Symfony\Component\HttpFoundation\Session\Session $session */
        $session = $event->getRequest()->getSession();
        $session->getFlashBag()->add('error', 'Votre compte a ete suspendu. Contactez '.$this->adminEmail.'.');
        $event->setResponse(new RedirectResponse($this->urlGenerator->generate('app_home')));
    }
}
