<?php

namespace App\Http\Middleware;

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

/**
 * Resolve the active UI language for each request: the signed-in user's saved
 * preference wins, then the session choice (so a guest on the login page can switch),
 * then the app default. Only known locales are honoured.
 */
class SetLocale
{
    /** Languages Clusev ships. Keep in sync with the lang/<code> directories + R16. */
    public const SUPPORTED = ['de', 'en'];

    public function handle(Request $request, Closure $next): Response
    {
        self::apply($request);

        return $next($request);
    }

    /**
     * Resolve + set the active locale: signed-in user's preference, then the session
     * choice, then the app default. Safe to call before the session is started — e.g.
     * from the exception handler for errors thrown before this middleware (CSRF 419,
     * unmatched-route 404, maintenance 503) — a missing session is simply skipped, so
     * those custom error pages still honour the user's language where it is known.
     */
    public static function apply(Request $request): void
    {
        $locale = config('app.locale');

        if ($request->hasSession()) {
            $locale = $request->user()?->locale
                ?? $request->session()->get('locale')
                ?? $locale;
        }

        if (in_array($locale, self::SUPPORTED, true)) {
            app()->setLocale($locale);
        }
    }
}
