<?php

namespace App\Http\Middleware;

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

class UpdateSessionGuard
{
    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        return $next($request);
    }

    /**
     * Handle tasks after the response has been sent to the browser.
     *
     * This method updates both the guard and user_id columns in the sessions table
     * to reflect which authentication guard is currently active for the session.
     * This prevents conflicts when multiple profile types (User, Bank, Organization)
     * share the same ID number.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Symfony\Component\HttpFoundation\Response  $response
     * @return void
     */
    public function terminate(Request $request, Response $response): void
    {
        // Only update if using database sessions
        if (config('session.driver') !== 'database') {
            return;
        }

        // Get the session ID
        $sessionId = $request->session()->getId();

        if (!$sessionId) {
            return;
        }

        // Get the active guard from session (defaults to 'web')
        $activeGuard = $request->session()->get('active_guard', 'web');

        // Get the authenticated user ID for the active guard
        $userId = \Illuminate\Support\Facades\Auth::guard($activeGuard)->id();

        // If no user is authenticated on the active guard, fall back to default guard
        if (!$userId) {
            $userId = \Illuminate\Support\Facades\Auth::id();
        }

        // Update both guard and user_id columns in the sessions table
        try {
            $updateData = ['guard' => $activeGuard];

            // Only update user_id if we have one
            if ($userId) {
                $updateData['user_id'] = $userId;
            }

            DB::table(config('session.table', 'sessions'))
                ->where('id', $sessionId)
                ->update($updateData);
        } catch (\Exception $e) {
            // Silently fail - don't break the application if guard column doesn't exist yet
            // This can happen during migration or if the migration hasn't run
        }
    }
}
