<?php

declare(strict_types=1);

use Inpsyde\MultilingualPress\Framework\Api\Translations;
use Inpsyde\MultilingualPress\Framework\Http\ServerRequest;
use Inpsyde\MultilingualPress\Framework\Service\Container;
use Inpsyde\MultilingualPress\Module\Redirect\AcceptLanguageParser;
use Inpsyde\MultilingualPress\Module\Redirect\GeoLocation\GeolocationFinder;
use Inpsyde\MultilingualPress\Module\Redirect\RedirectTarget\LanguageNegotiator;
use Inpsyde\MultilingualPress\Module\Redirect\ServiceProvider as RedirectModule;
use Inpsyde\MultilingualPress\Module\Redirect\Settings\Repository\Repository;

(static function (Container $container) {
    /**
     * Configuration for the user languages included in the Accept-Language header as
     * a map of language codes to priorities.
     *
     * @return array<string, float> A map of language codes to priorities.
     */
    $container->share(
        RedirectModule::CONFIGURATION_NAME_FOR_REDIRECT_USER_LANGUAGES,
        static function (Container $container): array {
            $parser = $container->get(AcceptLanguageParser::class);
            $request = $container->get(ServerRequest::class);
            $fields = $parser->parseHeader($request->header('Accept-Language'));

            if (!$fields) {
                return [];
            }

            $userLanguages = [];
            foreach ($fields as $code => $priority) {
                $userLanguages[$code] = $priority;
                if (!strpos($code, '-')) {
                    continue;
                }
                $code = strtok($code, '-');
                if (!isset($userLanguages[$code])) {
                    $userLanguages[$code] = $priority;
                }
            }

            return $userLanguages;
        }
    );

    $container->share(
        LanguageNegotiator::class,
        static function (Container $container): LanguageNegotiator {
            $settingsRepository = $container->get(Repository::class);

            return new LanguageNegotiator(
                $container->get(Translations::class),
                $container->get(Repository::class),
                $container->get(RedirectModule::CONFIGURATION_NAME_FOR_REDIRECT_USER_LANGUAGES),
                $container->get(GeolocationFinder::class),
                $settingsRepository->settingValue(Repository::MODULE_SETTING_REDIRECT_TYPE)
            );
        }
    );
}
)($container); //phpcs:disable VariableAnalysis.CodeAnalysis.VariableAnalysis.UndefinedVariable
