<?php

namespace App\Http\Middleware;

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

class SetLocale
{
    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        app()->setLocale($this->resolveLocale($request));

        return $next($request);
    }

    private function resolveLocale(Request $request): string
    {
        $supportedLocales = config('app.supported_locales', ['fr', 'en']);
        $requestedLocale = $request->query('locale') ?: $request->header('X-Locale');

        if (is_string($requestedLocale)) {
            $normalizedLocale = $this->normalizeLocale($requestedLocale);

            if (in_array($normalizedLocale, $supportedLocales, true)) {
                return $normalizedLocale;
            }
        }

        return $request->getPreferredLanguage($supportedLocales) ?? config('app.locale');
    }

    private function normalizeLocale(string $locale): string
    {
        $locale = strtolower(str_replace('_', '-', $locale));

        return explode('-', $locale)[0];
    }
}
