<?php

namespace App\Http\Middleware;

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

class SetLanguage
{
    /**
     * Handle an incoming request.
     *
     * @param  Closure(Request): (Response)  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        if ($request->validate([
            'lang' => ['nullable', 'string', Rule::in(array_keys(config('app.locales')))],
        ])) {
            app()->setLocale($request->lang);
        }

        return $next($request);
    }
}
