<?php

namespace Modules\SaasSwitcher\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\DB;
use Modules\SaasSwitcher\Support\ProjectRegistry;

/**
 * Swaps the application's default DB connection to the impersonated project's
 * connection for the whole session. No-op until a project user is actually
 * impersonated, so the super-admin keeps using the host (default `mysql`)
 * connection while browsing the chooser / user picker.
 *
 * SESSION_DRIVER=file, so the connection swap never disturbs the session.
 */
class ResolveProjectConnection
{
    public function handle(Request $request, Closure $next)
    {
        $key             = session(config('saasswitcher.session_key', 'saas_project'));
        $isImpersonating = session(config('saasswitcher.impersonating_key', 'saas_impersonating'));

        if ($key && $isImpersonating && ProjectRegistry::exists($key)) {
            $connection = ProjectRegistry::connection($key);

            Config::set('database.default', $connection);
            DB::setDefaultConnection($connection);

            $request->attributes->set('saas_project', $key);
            view()->share('saasProject', ProjectRegistry::get($key));
        }

        return $next($request);
    }
}
