<?php

declare(strict_types=1);

namespace App\Http\Middleware;

use App\Services\Localization\LocaleResolver;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\App;
use Symfony\Component\HttpFoundation\Response;

class ApplyResolvedLocale
{
    public function __construct(private LocaleResolver $resolver) {}

    public function handle(Request $request, Closure $next, ?string $plane = null): Response
    {
        $context = $this->resolver->resolve($request, $plane);

        App::setLocale($context['locale']);
        Carbon::setLocale($context['locale']);

        $request->attributes->set(LocaleResolver::REQUEST_ATTRIBUTE, $context);

        return $next($request);
    }
}
