<?php
namespace App\Security\Authentication;

use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Exception\RouteNotFoundException;
use Symfony\Component\Routing\Generator\UrlGenerator;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Http\Authentication\AuthenticationSuccessHandlerInterface;

class AuthenticationSuccessHandler implements AuthenticationSuccessHandlerInterface
{
    public function onAuthenticationSuccess(Request $request, TokenInterface $token): JsonResponse
    {
        $user = $token->getUser();
        // if user is already logged in, don't display the login page again
        if ($user->isGranted('ROLE_USER')) {
            $homePage = ($user->getUrlHomepage()) ? $user->getUrlHomepage() : 'list_agents';
            try {
                $urlGenerator = new UrlGenerator();
                $url = $urlGenerator->generate($homePage);
                return $this->redirectToRoute($homePage);
            } catch (RouteNotFoundException $e) {
                return $this->redirectToRoute('list_agents');
            };
        }
    }
}