<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class LoadTenant
{
    public function handle(Request $request, Closure $next)
    {
        try {
Log::info('🔄 Requête reçue au début du middleware loadtenant', [
    'request' => $request->toArray()
]);            // 🔹 1. Récupérer redirecturl depuis query, body ou header
            $redirectUrl = $request->query('redirectUrl')
                ?? $request->input('redirecturl')
                ?? $request->header('X-Redirect-Url');

            Log::info('🔄 redirecturl reçu', ['value' => $redirectUrl]);

            if (!$redirectUrl) {
                return response()->json([
                    'success' => false,
                    'message' => 'redirecturl manquant'
                ], 400);
            }

            // 🔹 2. Extraire le sous-domaine avant .eservices
            // ex: iatf.eservices.bj → iatf
            // 1️⃣ Extraire le host
$host = parse_url($redirectUrl, PHP_URL_HOST); // "iatf.eservices.sigan.bj"

// 2️⃣ Extraire la partie avant ".eservices"
$parts = explode('.eservices', $host);
$namebase = $parts[0] ?? null; 



            if (!$namebase) {
                return response()->json([
                    'success' => false,
                    'message' => 'Format redirecturl invalide'
                ], 400);
            }

            Log::info('✅ Namebase extrait', ['namebase' => $namebase]);

            // 🔹 3. Changer dynamiquement la base tenant
            changeTenantEnv(['database' => $namebase]);

            // 🔹 4. Forcer la reconnexion
            DB::purge('tenant');
            DB::reconnect('tenant');

            Log::info('✅ Connexion tenant active', [
                'database' => DB::connection('tenant')->getDatabaseName()
            ]);

            return $next($request);

        } catch (\Throwable $e) {

            Log::error('❌ Erreur LoadTenant', [
                'message' => $e->getMessage()
            ]);

            return response()->json([
                'success' => false,
                'message' => 'Impossible de charger le tenant'
            ], 500);
        }
    }
}
