<?php

declare(strict_types=1);

namespace TechnoArtisan\FilamentCms\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\URL;
use Symfony\Component\HttpFoundation\Response;
use TechnoArtisan\FilamentCms\Configs\Localization as LocalizationConfig;

readonly class Localization
{
    public function __construct(private LocalizationConfig $config)
    {
    }

    /**
     * Handle an incoming request.
     *
     * @param  Closure(Request): (Response)  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        $locale = $request->segment($this->config->segment);

        // set the "segment" (path) to locale
        URL::defaults([$this->config->variable => $request->segment($this->config->segment)]);

        // on "/" (root) its always empty
        if (empty($locale)) {
            $locale = $request->getPreferredLanguage($this->config->availableLocales);
        }

        if (in_array($locale, $this->config->availableLocales, true)) {
            app()->setLocale($locale);
        } else {
            app()->setLocale($this->config->fallbackLocale);
        }

        return $next($request);
    }
}
