<?php

namespace App\Http\Middleware;

use App\Services\LocalizationService;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class SetLocale
{
    public function __construct(private LocalizationService $localization)
    {
    }

    public function handle(Request $request, Closure $next): Response
    {
        $requestedLocale = $request->session()->get('locale');
        $language = $this->localization->activate(is_string($requestedLocale) ? $requestedLocale : null);

        if ($language && $requestedLocale !== $language->code) {
            $request->session()->put('locale', $language->code);
        }

        return $next($request);
    }
}
