<?php

declare(strict_types=1);

namespace KupShop\TwoFactorBundle\EventSubscriber;

use Scheb\TwoFactorBundle\Security\Authentication\Token\TwoFactorTokenInterface;
use Symfony\Bundle\FrameworkBundle\Routing\Router;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\Security\Http\Event\LoginSuccessEvent;

class LoginSubscriber implements EventSubscriberInterface
{
    public static function getSubscribedEvents()
    {
        return [
            LoginSuccessEvent::class => [
                ['redirectToTwoFactorForm', 200],
            ],
        ];
    }

    /*
     * By default after login, the user is redirected to homepage/next url which redirects him to 2FA form - this does not work with CDN/Cache.
     * This forces user in 2FA process to be redirected to 2FA form directly.
    */
    public function redirectToTwoFactorForm(LoginSuccessEvent $event)
    {
        if ($event->getAuthenticatedToken() instanceof TwoFactorTokenInterface) {
            $event->setResponse(new RedirectResponse(path('2fa_login', referenceType: Router::ABSOLUTE_URL)));
        }
    }
}
