<?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;

use Symfony\Component\EventDispatcher\Attribute\AsEventListener;
use Symfony\Component\HttpKernel\Event\RequestEvent;

/**
 * Fixes the ICU locale for PHP's default locale if the request locale is not a valid ICU locale.
 *
 * For example, "prs" (Dari) is a valid language code but not supported by all ICU versions.
 * In such cases, we map it to a similar supported locale like "fa_AF".
 */
final class IcuLocaleListener
{
    /**
     * @see \Ferienpass\CmsBundle\Routing\LocaleRouteProviderDecorator::MAP
     */
    private const array MAP = [
        'prs' => 'fa_AF',
    ];

    #[AsEventListener('kernel.request', priority: 14)] // After LocaleListener (16)
    public function onKernelRequest(RequestEvent $event): void
    {
        $locale = $event->getRequest()->getLocale();

        if (isset(self::MAP[$locale])) {
            try {
                // Check if the mapped locale is valid for NumberFormatter
                new \NumberFormatter(self::MAP[$locale], \NumberFormatter::CURRENCY);

                \Locale::setDefault(self::MAP[$locale]);
            } catch (\ValueError) {
                // If even the mapped locale is invalid, we don't do anything
            }
        }
    }
}
