<?php

namespace App\Http\Controllers\Auth;

use App\Models\User;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class TwoFactorGuard
{
    /**
     * If the just-authenticated user has confirmed 2FA, log them out again
     * and stash the pending id in the session so the challenge screen can
     * finalise the login once the code is verified.
     */
    public static function intercept(Request $request, $user, bool $remember): ?RedirectResponse
    {
        if (! $user instanceof User || ! $user->hasTwoFactor()) {
            return null;
        }

        $userId = $user->getKey();
        Auth::logout();
        $request->session()->put('two_factor_pending_user_id', $userId);
        $request->session()->put('two_factor_pending_remember', $remember);
        $request->session()->forget('2fa_passed');

        return redirect('/2fa/challenge');
    }
}
