<?php

declare(strict_types=1);

namespace Builder\Core\Http\Middleware;

use Builder\Core\Foundation\Middleware\BuilderAuth;
use Builder\Core\Models\Language;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

final class SetLocale
{
    public function handle(Request $request, Closure $next): Response
    {
        $guard = BuilderAuth::guard();
        $user = $request->user($guard);

        $supported = Language::activeLocales()->pluck('code')->all();

        if ($user && isset($user->locale) && in_array($user->locale, $supported, true)) {
            app()->setLocale($user->locale);
        }

        return $next($request);
    }
}
