<?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\CmsBundle\EventListener\Routing;

use Ferienpass\CmsBundle\Routing\LocaleRouteProviderDecorator;
use Symfony\Component\EventDispatcher\Attribute\AsEventListener;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\Event\RequestEvent;

final class LocaleRedirectListener
{
    #[AsEventListener('kernel.request', priority: 16)]
    public function onKernelRequest(RequestEvent $event): void
    {
        if (!$event->isMainRequest()) {
            return;
        }

        $request = $event->getRequest();
        if ('/' !== $request->getPathInfo()) {
            return;
        }

        // Only redirect if the referer is NOT from the same host to allow switching back to the default language.
        $referer = $request->headers->get('referer');
        if (null !== $referer && (parse_url($referer, \PHP_URL_HOST) === $request->getHost())) {
            return;
        }

        $availableLocales = array_keys(LocaleRouteProviderDecorator::MAP);
        $preferredLocale = $request->getPreferredLanguage($availableLocales);

        if (null === $preferredLocale) {
            return;
        }

        $prefix = LocaleRouteProviderDecorator::MAP[$preferredLocale] ?? '';
        if ('' === $prefix) {
            return;
        }

        $qs = $request->getQueryString();
        $target = '/'.$prefix.'/'.($qs ? '?'.$qs : '');

        $event->setResponse(new RedirectResponse($target, 302));
    }
}
