<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\App;
use Symfony\Component\HttpFoundation\Response;

class SetApiLocale
{
    public function handle(Request $request, Closure $next): Response
    {
        if (! $request->is('api/*')) {
            return $next($request);
        }

        $supportedLocales = config('app.supported_locales', ['es', 'en']);
        $acceptLanguage = $request->header('Accept-Language');
        $locale = is_string($acceptLanguage) && $acceptLanguage !== ''
            ? $request->getPreferredLanguage($supportedLocales)
            : null;
        $locale ??= config('app.locale', 'es');

        App::setLocale($locale);

        $response = $next($request);
        $response->headers->set('Content-Language', $locale);
        $response->setVary('Accept-Language', false);

        return $response;
    }
}
