<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Http\Requests\Auth\LoginRequest;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\View\View;

class AuthenticatedSessionController extends Controller
{
    /**
     * Display the login view.
     */
    public function create(): View
    {
        return view('auth.login');
    }

    /**
     * Handle an incoming authentication request.
     */
    public function store(LoginRequest $request): RedirectResponse
    {
        $request->authenticate();

        // If the user has confirmed 2FA, intercept: log them back out, stash
        // their id in the session, and redirect to the OTP challenge.
        $user = Auth::user();
        if ($user && $user->two_factor_confirmed_at) {
            Auth::guard('web')->logout();
            $request->session()->put([
                'two_factor.pending_user_id' => $user->id,
                'two_factor.remember' => $request->boolean('remember'),
                'two_factor.intended' => $request->session()->pull('url.intended'),
            ]);
            return redirect()->route('two-factor.challenge');
        }

        $request->session()->regenerate();

        return redirect()->intended(route('dashboard', absolute: false));
    }

    /**
     * Destroy an authenticated session.
     */
    public function destroy(Request $request): RedirectResponse
    {
        Auth::guard('web')->logout();

        $request->session()->invalidate();

        $request->session()->regenerateToken();

        return redirect('/');
    }
}
