<?php

/*
 * This file is part of the Serenity package.
 *
 * (c) CP Creation <web@cpcreation.fr>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Serenity\SaasBundle\Authentication;

use Serenity\SaasBundle\Doctrine\Repository\ProjectRepository;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Http\Authentication\AuthenticationSuccessHandlerInterface;

final readonly class AdminSuccessHandler implements AuthenticationSuccessHandlerInterface
{
    public function __construct(
        private RouterInterface $router,
        private ProjectRepository $projectRepository,
    ) {
    }

    public function onAuthenticationSuccess(Request $request, TokenInterface $token): Response
    {
        $user = $token->getUser();

        if (!$user instanceof UserInterface) {
            throw new \LogicException('Authenticated user must implement UserInterface.');
        }

        $projects = $this->projectRepository->getProjectsByTenant($user);
        $request->setRequestFormat('html');
        if (1 === \count($projects)) {
            $request->getSession()->set('project_identifier', $projects[0]->getIdentifier());

            return new RedirectResponse($this->router->generate('admin_index'), Response::HTTP_SEE_OTHER, ['Content-Type' => 'text/html']);
        }

        return new RedirectResponse($this->router->generate('admin_saas_select_project'), Response::HTTP_SEE_OTHER, ['Content-Type' => 'text/html']);
    }
}
