<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\View;
use Symfony\Component\HttpFoundation\Response;

class SetLocale
{
    /** @var list<string> */
    public const SUPPORTED = ['en', 'fa'];

    /**
     * @param  Closure(Request): (Response)  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        $locale = $this->resolveLocale($request) ?? $this->defaultLocale();

        App::setLocale($locale);

        if ($request->session()->get('locale') !== $locale) {
            $request->session()->put('locale', $locale);
        }

        $direction = $locale === 'fa' ? 'rtl' : 'ltr';
        $htmlLang = $locale === 'fa' ? 'fa' : 'en';

        View::share('direction', $direction);
        View::share('html_lang', $htmlLang);

        return $next($request);
    }

    private function defaultLocale(): string
    {
        $default = config('app.locale', 'en');

        if (! is_string($default) || ! in_array($default, self::SUPPORTED, true)) {
            return 'en';
        }

        return $default;
    }

    private function resolveLocale(Request $request): ?string
    {
        $fromQuery = $request->query('locale');

        if (is_string($fromQuery) && in_array($fromQuery, self::SUPPORTED, true)) {
            return $fromQuery;
        }

        $fromSession = $request->session()->get('locale');

        if (is_string($fromSession) && in_array($fromSession, self::SUPPORTED, true)) {
            return $fromSession;
        }

        $fromCookie = $request->cookie('locale');

        if (is_string($fromCookie) && in_array($fromCookie, self::SUPPORTED, true)) {
            return $fromCookie;
        }

        return null;
    }
}
