<?php

namespace CpCreation\VitiCore\Bridge\Symfony\Bundle\Controller\Site;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Routing\RouterInterface;

final class LocaleController extends AbstractController
{
    public function __construct(
        private readonly RouterInterface $router,
        private readonly RequestStack $requestStack,
    ) {
    }

    private function getSession(): ?SessionInterface
    {
        return $this->requestStack->getSession();
    }
    
    #[Route('/request/locale/{locale}', name: 'setLocale')]
    public function setLocale(Request $request, ?string $locale = null): RedirectResponse
    {
        if ($locale) {
            $this->getSession()->set('_locale', $locale);
        }

        $url = $request->headers->get('referer');
        if (!$url) {
            $url = $this->router->generate('homepage');
        }

        return new RedirectResponse($url);
    }
}
