<?php

namespace App\Http\Middleware;

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

class SetLocale
{
    public const SUPPORTED = ['tr', 'en'];

    public function handle(Request $request, Closure $next): Response
    {
        $userLocale = $request->user()?->locale;
        $storedLocale = $request->session()->get('locale', $request->cookie('locale'));
        $locale = in_array($userLocale, self::SUPPORTED, true)
            ? $userLocale
            : (in_array($storedLocale, self::SUPPORTED, true) ? $storedLocale : config('app.locale', 'tr'));

        if (! in_array($locale, self::SUPPORTED, true)) {
            $locale = 'tr';
        }

        App::setLocale($locale);
        $request->session()->put('locale', $locale);

        return $next($request);
    }
}
