<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class SetLocale
{
    public function handle(Request $request, Closure $next): Response
    {
        $locale = $request->query('locale')
            ?? $request->session()->get('locale')
            ?? $request->user()?->preferred_locale
            ?? config('esports.default_locale', 'en');

        if (! in_array($locale, config('esports.supported_locales', ['en', 'ar']), true)) {
            $locale = config('esports.default_locale', 'en');
        }

        if ($request->has('locale')) {
            $request->session()->put('locale', $locale);
        }

        app()->setLocale($locale);

        return $next($request);
    }
}
