<?php

namespace App\Modules\Settings\Localization\Middleware;

use App\Modules\Settings\Localization\Models\Language;
use App\Modules\Settings\Localization\Services\LanguageService;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\View;
use Symfony\Component\HttpFoundation\Response;

class SetLocale
{
    public function __construct(
        private readonly LanguageService $languageService,
    ) {}

    public function handle(Request $request, Closure $next): Response
    {
        $sessionCode = $request->session()->get('app_locale');
        $user = $request->user();
        if ($sessionCode === null && $user !== null && $user->tenant?->locale) {
            $active = $this->languageService->findActiveByCode((string) $user->tenant->locale);
        } else {
            $active = $this->resolveLanguage($sessionCode);
        }

        if ($active instanceof Language) {
            App::setLocale($active->code);
        }

        View::share([
            'currentLanguage' => $active,
            'isRtl' => (bool) ($active?->is_rtl),
            'availableLanguages' => $this->languageService->allActive(),
        ]);

        return $next($request);
    }

    private function resolveLanguage(?string $sessionCode): ?Language
    {
        if ($sessionCode) {
            $match = $this->languageService->findActiveByCode($sessionCode);
            if ($match) {
                return $match;
            }
        }

        return $this->languageService->default();
    }
}
