<?php

namespace App\Http\Middleware;

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

class SetLocale
{
    /**
     * @var array<int, string>
     */
    private array $supportedLocales = ['ro', 'ru', 'en', 'it'];

    public function handle(Request $request, Closure $next): Response
    {
        $routeLocale = $request->route('locale');
        $sessionLocale = $request->session()->get('locale');
        $locale = null;

        if (is_string($routeLocale) && in_array($routeLocale, $this->supportedLocales, true)) {
            $locale = $routeLocale;
        } elseif (is_string($sessionLocale) && in_array($sessionLocale, $this->supportedLocales, true)) {
            $locale = $sessionLocale;
        } else {
            $locale = 'ro';
        }

        App::setLocale($locale);
        $request->session()->put('locale', $locale);

        return $next($request);
    }
}
