<?php

declare(strict_types=1);

namespace App\Http\Middleware;

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

class SetAdminLocale
{
    public function handle(Request $request, Closure $next): Response
    {
        /** @var array<string, string> $supported */
        $supported = config('dberp.admin.locales', []);

        $sessionLocale = $request->session()->get('dberp_admin_locale');
        $locale = is_string($sessionLocale) && array_key_exists($sessionLocale, $supported)
            ? $sessionLocale
            : (string) config('app.locale');

        app()->setLocale($locale);
        Carbon::setLocale($locale);

        return $next($request);
    }
}
