<?php

declare(strict_types=1);

/*
 * This file is part of the Ferienpass package.
 *
 * (c) Richard Henkenjohann <richard@ferienpass.online>
 *
 * For more information visit the project website <https://ferienpass.online>
 * or the documentation under <https://docs.ferienpass.online>.
 */

namespace Ferienpass\AdminBundle\Controller;

use Ferienpass\CoreBundle\Entity\User;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Bundle\SecurityBundle\Security;
use Symfony\Component\DependencyInjection\Attribute\Autowire;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Security\Core\Authentication\Token\SwitchUserToken;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
use Symfony\Component\Security\Core\User\UserProviderInterface;
use Symfony\Component\Security\Http\Attribute\IsGranted;

#[Route('/vorschau')]
#[IsGranted('ROLE_ADMIN')]
class FrontendPreviewController extends AbstractController
{
    public function __construct(
        #[Autowire(service: 'security.user.provider.concrete.ferienpass_user_provider')]
        private readonly UserProviderInterface $userProvider,
        private readonly Security $security,
    ) {
    }

    /**
     * Without a username this is a harmless GET shortcut that just opens the
     * frontend. Impersonating a frontend member, however, is a state-changing
     * action: it must be a POST guarded by a CSRF token so it cannot be
     * triggered by a cross-site GET.
     */
    #[Route('/{username?}', name: 'admin_frontend_preview', methods: ['GET', 'POST'])]
    public function __invoke(?string $username, Request $request): Response
    {
        if (null !== $username) {
            $this->denyAccessUnlessGranted('ROLE_ALLOWED_TO_SWITCH');

            if (!$request->isMethod('POST')) {
                throw $this->createAccessDeniedException('Impersonation requires a POST request.');
            }

            if (!$this->isCsrfTokenValid('submit', (string) $request->request->get('_token'))) {
                throw $this->createAccessDeniedException('Invalid CSRF token.');
            }

            if (!($frontendUser = $this->userProvider->loadUserByIdentifier($username)) instanceof User) {
                throw $this->createNotFoundException();
            }

            // The contao_frontend firewall does not enable Symfony's native
            // switch_user, so we still seed the session token by hand. We build
            // a SwitchUserToken (carrying the impersonating admin's original
            // token) instead of a plain UsernamePasswordToken so the
            // impersonation is detectable downstream — e.g. for an impersonator
            // banner or to flag the request to Varnish.
            $originalToken = $this->security->getToken() ?? new UsernamePasswordToken($frontendUser, 'contao_frontend', $frontendUser->getRoles());

            $token = new SwitchUserToken($frontendUser, 'contao_frontend', $frontendUser->getRoles(), $originalToken);

            $session = $request->getSession();
            $session->set('_security_contao_frontend', serialize($token));
        }

        return $this->redirect('/', 303);
    }
}
