<?php

namespace App\Http\Middleware;

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

class DetectRegion
{
    public function handle(Request $request, Closure $next)
    {

      
        if ($request->session()->has('db_connection')) {
            $connection = $request->session()->get('db_connection');
            DB::setDefaultConnection($connection);
            config(['database.default' => $connection]);
            \Log::info('DetectRegion', [
                'has_session' => $request->session()->has('db_connection'),
                'connection' => $request->session()->get('db_connection'),
                'db_default' => config('database.default'),
                'auth_check' => Auth::check(),
                'url' => $request->url(),
            ]);

            return $next($request);
        }

        // Only GeoIP detect for guests with no session
        $iso = rescue(
            fn() => strtoupper(geoip()->getLocation($request->ip())->iso_code),
            'US'
        );

        $connection = match ($iso) {
            'CA' => 'CA',
            'US' => 'US',
            default => 'mysql',
        };

        $request->session()->put('db_connection', $connection);
        DB::setDefaultConnection($connection);
        config(['database.default' => $connection]);
        \Log::info('DetectRegion', [
            'has_session' => $request->session()->has('db_connection'),
            'connection' => $request->session()->get('db_connection'),
            'db_default' => config('database.default'),
            'auth_check' => Auth::check(),
            'url' => $request->url(),
        ]);
        return $next($request);
    }
}