<?php

namespace App\Security;

use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
use Symfony\Component\Security\Http\Authentication\AuthenticationSuccessHandlerInterface;

class LoginSuccessHandler implements AuthenticationSuccessHandlerInterface
{
    private const ROLE_ROUTES = [
        'ROLE_EMPLOYE' => 'app_admin_dashboard',
        'ROLE_REVENDEUR' => 'app_espace_prestataire_index',
        'ROLE_CUSTOMER' => 'app_espace_client_index',
    ];

    public function __construct(
        private RouterInterface $router,
        private AuthorizationCheckerInterface $authorizationChecker,
    ) {
    }

    public function onAuthenticationSuccess(Request $request, TokenInterface $token): RedirectResponse
    {
        foreach (self::ROLE_ROUTES as $role => $route) {
            if ($this->authorizationChecker->isGranted($role)) {
                return new RedirectResponse($this->router->generate($route));
            }
        }

        return new RedirectResponse($this->router->generate('app_home'));
    }
}
