<?php

namespace App\Http\Middleware;

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

class SetLocale
{
    /**
     * Handle an incoming request.
     *
     * @param  Closure(Request): (Response)  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        // 1. Logged-in user preference
        if (Auth::check() && Auth::user()->locale) {
            App::setLocale(Auth::user()->locale);

            return $next($request);
        }

        // 2. Session (guest or user override)
        if (session()->has('locale') && in_array($request->language, config('app.supported_locales'), true)) {
            App::setLocale(session('locale'));

            return $next($request);
        }

        // 3. Browser language
        $locale = $request->getPreferredLanguage(config('app.supported_locales'));

        if ($locale) {
            App::setLocale($locale);
        }

        return $next($request);
    }
}
