<?php

namespace App\EventSubscriber;

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

/**
 * Tant qu'un utilisateur authentifié n'est pas ACTIVE, il est dirigé vers l'onboarding
 * (/bienvenue) ou l'écran d'attente (/en-attente), et ne peut pas utiliser l'application.
 */
final class OnboardingGateSubscriber implements EventSubscriberInterface
{
    /** Routes accessibles quel que soit le statut. */
    private const ALLOWED_ROUTES = [
        'app_onboarding',
        'app_waiting',
        'app_logout',
        'app_login',
        'app_auth_send_code',
        'app_auth_verify',
        'app_auth_me',
    ];

    public function __construct(
        private readonly Security $security,
        private readonly UrlGeneratorInterface $urlGenerator,
    ) {
    }

    public static function getSubscribedEvents(): array
    {
        // Après le firewall (priorité 8) pour disposer de l'utilisateur authentifié.
        return [KernelEvents::REQUEST => ['onKernelRequest', 6]];
    }

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

        $user = $this->security->getUser();
        if (!$user instanceof User || $user->isActive()) {
            return;
        }

        $request = $event->getRequest();
        $path = $request->getPathInfo();
        // Laisser passer auth, assets, profiler.
        foreach (['/auth', '/api/auth', '/assets', '/_'] as $prefix) {
            if (str_starts_with($path, $prefix)) {
                return;
            }
        }

        $route = $request->attributes->get('_route');
        if (\in_array($route, self::ALLOWED_ROUTES, true)) {
            return;
        }

        $target = User::STATUS_ONBOARDING === $user->getStatus() ? 'app_onboarding' : 'app_waiting';
        $event->setResponse(new \Symfony\Component\HttpFoundation\RedirectResponse(
            $this->urlGenerator->generate($target)
        ));
    }
}
