<?php

/*
 * This file is part of the Serenity package.
 *
 * (c) CP Creation <web@cpcreation.fr>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Serenity\AdminBundle\EventListener;

use Symfony\Component\EventDispatcher\Attribute\AsEventListener;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;

#[AsEventListener(event: KernelEvents::REQUEST)]
readonly class AdminAccessListener
{
    public function __construct(private AuthorizationCheckerInterface $authorizationChecker, private RouterInterface $router)
    {
    }

    public function __invoke(RequestEvent $event): void
    {
        $request = $event->getRequest();
        $route = $request->attributes->get('_route');
        $path = $request->getPathInfo();

        // Vérifier si c'est la requête principale et si elle concerne /dashboard
        if (!$event->isMainRequest() || !preg_match('#^(/([a-z]{2}))?/dashboard#', $path)) {
            return;
        }

        // Ignorer la route de déconnexion de l'admin
        if ('admin_logout' === $route) {
            return;
        }

        // Rediriger vers l'accueil admin si l'utilisateur est déjà connecté et tente d'accéder à la page de connexion
        if ('admin_login' === $route && $this->authorizationChecker->isGranted('ADMIN_ROUTE')) {
            $event->setResponse(new RedirectResponse($this->router->generate('admin_index')));

            return;
        }

        // Rediriger vers la page de connexion si l'utilisateur n'a pas le droit d'accès à l'administration
        if ('admin_login' !== $route && !$this->authorizationChecker->isGranted('ADMIN_ROUTE')) {
            $event->setResponse(new RedirectResponse($this->router->generate('admin_login')));
        }
    }
}
