<?php

namespace App\EventSubscriber;

use App\Exception\UserNotVerifiedException;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\Security\Http\Authenticator\Passport\Passport;
use Symfony\Component\Security\Http\Event\CheckPassportEvent;
use Symfony\Component\Security\Http\Event\LoginFailureEvent;

class CheckVerifiedUserSubscriber implements EventSubscriberInterface
{

    public function __construct(private readonly RouterInterface $router)
    {
        // empty body
    }


    public function onCheckPassport(CheckPassportEvent $event)
    {
        $passport = $event->getPassport();
        /*
         * var User $user
         */
        $user = $passport->getUser();

        if (!$user->isVerified()) {
            throw new UserNotVerifiedException();
        }
    }


    public function onValidationFailure(LoginFailureEvent $failureEvent)
    {
        if (!$failureEvent->getException() instanceof UserNotVerifiedException) {
            return;
        }

        $request = $failureEvent->getRequest();
        $email = $failureEvent->getPassport()->getUser()->getEmail();
        $request->getSession()->set('non_verified_email', $email);

        $response = new RedirectResponse(
            $this->router->generate('security_resend_verify_email')
        );
        $failureEvent->setResponse($response);
    }


    public static function getSubscribedEvents(): array
    {
        return [
            CheckPassportEvent::class => ['onCheckPassport', -10],
            LoginFailureEvent::class => 'onValidationFailure'
        ];
    }
}