<?php

// src/EventListener/LocaleSubscriber.php
namespace App\EventListener;

use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpFoundation\RequestStack;

class LocaleSubscriber implements EventSubscriberInterface
{
    private string $defaultLocale;
    private RequestStack $requestStack;

    public function __construct(RequestStack $requestStack, string $defaultLocale = 'es')
    {
        $this->defaultLocale = $defaultLocale;
        $this->requestStack = $requestStack;
    }

    public function onKernelRequest(RequestEvent $event): void
    {
        $request = $event->getRequest();
        $locale = $request->getSession()->get('_locale', $this->defaultLocale);

        if ($request->attributes->get('_locale')) {
            $locale = $request->attributes->get('_locale');
        }

        $localeFromHeader = $request->getPreferredLanguage(['en', 'es']);
        if ($localeFromHeader) {
            $locale = $localeFromHeader;
        }

        $request->setLocale($locale);
    }

    public static function getSubscribedEvents(): array
    {
        return [
            KernelEvents::REQUEST => [['onKernelRequest', 20]],
        ];
    }
}
