<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Models\AuditLog;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class AuthenticatedSessionController extends Controller
{
    public function create()
    {
        return view('auth.login');
    }

    public function store(Request $request)
    {
        $credentials = $request->validate([
            'email' => ['required', 'email'],
            'password' => ['required'],
        ]);

        $remember = $request->filled('remember');

        if (Auth::attempt($credentials, $remember)) {
            $user = Auth::user();

            if ($user->two_factor_enabled && $user->two_factor_secret) {
                Auth::logout();
                $request->session()->put('2fa_user_id', $user->id);
                $request->session()->put('2fa_remember', $remember);
                return redirect()->route('2fa.challenge');
            }

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

            AuditLog::record('user.login', [
                'user_id'   => $user->id,
                'user_name' => $user->name,
                'details'   => ['email' => $user->email],
            ]);

            return redirect()->intended('/videos');
        }

        AuditLog::record('user.login.failed', [
            'user_id'   => null,
            'user_name' => null,
            'details'   => ['email' => $credentials['email']],
        ]);

        return back()->withErrors([
            'email' => 'The provided credentials do not match our records.',
        ]);
    }

    public function destroy(Request $request)
    {
        $user = Auth::user();
        if ($user) {
            AuditLog::record('user.logout', [
                'user_id'   => $user->id,
                'user_name' => $user->name,
            ]);
        }
        Auth::logout();
        $request->session()->invalidate();
        $request->session()->regenerateToken();
        return redirect('/videos');
    }
}
