<?php

namespace App\Http\Middleware;

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

class TenantMiddleware
{
    /**
     * Handle an incoming request.
     */
    public function handle(Request $request, Closure $next): Response
    {

        if (! $request->user()) {
            return redirect('/');
        }

        $this->setupTenantConnection($request->user());

        return $next($request);
    }

    /**
     * Set up the tenant database connection
     */
    public function setupTenantConnection($user = null)
    {
        $user = $user ?: auth()->user();

        if ($user) {
            Log::info('Setting database connection', [
                'database' => $user->tenant_database,
                'username' => $user->tenant_username,
                'password' => $user->tenant_password
            ]);

            $connection = [
                'driver' => 'mysql',
                'host' => '127.0.0.1',
                'port' => '3306',
                'database' => $user->tenant_database,
                'username' => $user->tenant_username,
                'password' => $user->tenant_password,
            ];

            config(['database.connections.tenant' => $connection]);

            config(['database.default' => 'tenant']);
            DB::purge('tenant');
            DB::reconnect('tenant');

            session(['currentClient' => $user->tenant_database]);

            session(['db_connection' => $connection]);

            Log::info('Current database after setup: ' . DB::connection()->getDatabaseName());
            Log::info('Current default connection: ' . DB::getDefaultConnection());
        }
    }
}
