<?php

namespace App\Http\Middleware;

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

class SetUserLanguage
{
    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        $language = substr($request->header('Accept-Language'), 0, 2);
        $language = LanguageEnum::fromString($language);

        if ($language) {
            App::setLocale($language->value);
        } else {
            App::setLocale(LanguageEnum::PORTUGUESE->value);
        }

        return $next($request);
    }
}
