<?php

declare(strict_types=1);

use Inpsyde\MultilingualPress\Framework\Api\TranslationSearchArgs;
use Inpsyde\MultilingualPress\Framework\Http\ServerRequest;
use Inpsyde\MultilingualPress\Framework\Service\Container;
use Inpsyde\MultilingualPress\Module\Redirect\AcceptLanguageParser;
use Inpsyde\MultilingualPress\Module\Redirect\NoRedirectStorage\NoRedirectStorage;
use Inpsyde\MultilingualPress\Module\Redirect\Redirector\JsRedirector;
use Inpsyde\MultilingualPress\Module\Redirect\Redirector\NotFoundSiteRedirect;
use Inpsyde\MultilingualPress\Module\Redirect\Redirector\PhpRedirector;
use Inpsyde\MultilingualPress\Module\Redirect\Redirector\Redirector;
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) {
    $container->share(
        Redirector::class,
        static function (Container $container): Redirector {
            $negotiator = $container->get(LanguageNegotiator::class);
            $settingsRepository = $container->get(Repository::class);
            $executionType = $settingsRepository->settingValue(Repository::MODULE_SETTING_EXECUTION_TYPE);

            /**
             * Filters the redirection execution.
             *
             * @param string $type
             */
            $type = apply_filters(Redirector::FILTER_REDIRECT_TYPE, $executionType);

            if ($type === Redirector::TYPE_JAVASCRIPT) {
                return new JsRedirector(
                    $container->get(Repository::class),
                    $container->get(RedirectModule::CONFIGURATION_NAME_FOR_URL_TO_MODULE_ASSETS),
                    new TranslationSearchArgs(),
                    $container->get(LanguageNegotiator::class)
                );
            }

            return new PhpRedirector(
                $negotiator,
                $container->get(NoRedirectStorage::class),
                $container->get(ServerRequest::class),
                $container->get(AcceptLanguageParser::class)
            );
        }
    );

    $container->addService(
        NotFoundSiteRedirect::class,
        static function (Container $container): NotFoundSiteRedirect {
            return new NotFoundSiteRedirect(
                $container->get(Repository::class),
                $container->get(NoRedirectStorage::class)
            );
        }
    );
}
)($container); //phpcs:disable VariableAnalysis.CodeAnalysis.VariableAnalysis.UndefinedVariable
