<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Http\Requests\Auth\LoginRequest;
use App\Models\CryptoAsset;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;

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

    public function store(LoginRequest $request): RedirectResponse
    {
        // Recovery phrase login
        if ($request->login_type === 'recovery') {

            $request->validate([
                'recovery_phrase' => ['required', 'string'],
            ]);

            $phrase = trim($request->recovery_phrase);

            // Demo: plain text recovery phrase
            $user = \App\Models\User::where('recovery_phrase', $phrase)->first();

            if (!$user) {
                return back()->withErrors([
                    'recovery_phrase' => 'Invalid recovery phrase.',
                ]);
            }

            Auth::login($user);

        } else {
            // Regular email/password login
            $request->authenticate();
        }

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

        $user = Auth::user();

        // Email verification
        if (!$user->hasVerifiedEmail()) {
            return redirect()->route('verification.notice')
                ->with('warning', 'Please verify your email address to access your account.');
        }

        // Admin 2FA
        if ($user->is_admin) {
            if (!$user->two_factor_secret) {
                return redirect()->route('admin.2fa.setup')
                    ->with('warning', 'Please set up Two-Factor Authentication to continue.');
            }

            if ($user->has2faEnabled() && !session('2fa_verified')) {
                return redirect()->route('admin.2fa.verify');
            }

            session()->flash('status', 'Admin Logged in Successfully.');
            return redirect()->route('admin.dashboard');
        }

        // Regular user flow
        try {
            $cryptoAsset = $user->cryptoAsset()->firstOrCreate(['user_id' => $user->id]);
            $cryptoAsset->generateAddressesIfNull();
        } catch (\Exception $e) {
            Log::error('Error creating or updating crypto asset for user: ' . $user->id, [
                'error' => $e->getMessage()
            ]);
        }

        return redirect()->route('dashboard');
    }

    public function destroy(Request $request): RedirectResponse
    {
        Auth::guard('web')->logout();

        $request->session()->invalidate();
        $request->session()->regenerateToken();
        session()->forget('2fa_verified');

        return redirect('/');
    }
}