<?php

namespace App\Http\Middleware;

use App\Tenancy\TenantManager;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Auth;
use Carbon\Carbon;

class SetLocale
{
    private const SUPPORTED = ['ro', 'ru', 'en'];

    public function handle(Request $request, Closure $next)
    {
        $locale = $this->resolve($request);

        App::setLocale($locale);
        Carbon::setLocale($locale);

        return $next($request);
    }

    private function resolve(Request $request): string
    {
        // Cookie wins first — set explicit de utilizator via /locale/{lang},
        // supraviețuiește regenerării sesiunii și subdomeniilor separate.
        $cookie = $request->cookie('app_locale');
        if ($cookie && in_array($cookie, self::SUPPORTED, true)) {
            return $cookie;
        }

        // Session may not be started yet on early-stage middleware paths.
        if ($request->hasSession()) {
            $session = $request->session()->get('locale');
            if ($session && in_array($session, self::SUPPORTED, true)) {
                return $session;
            }
        }

        $user = Auth::user();
        if ($user && ! empty($user->locale) && in_array($user->locale, self::SUPPORTED, true)) {
            return $user->locale;
        }

        $tenant = app(TenantManager::class)->current();
        $tenantLang = $tenant?->settings['language'] ?? null;
        if ($tenantLang && in_array($tenantLang, self::SUPPORTED, true)) {
            return $tenantLang;
        }

        // Hard-code fallback la 'ro' — indiferent de APP_LOCALE din env,
        // portal-ul client-facing e livrat cu RO ca implicit safe (RU disponibil via switcher).
        return 'ro';
    }
}
