<?php

namespace App\Nexus\Http\Controllers;

use App\Nexus\Engine\NexusAuditLogger;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\Str;

class NexusAuthController extends Controller
{
    /**
     * Show the NEXUS login page.
     * Redirects to dashboard if already authenticated.
     */
    public function showLogin()
    {
        if (Auth::guard('nexus')->check()) {
            return redirect('/nexus/dashboard');
        }

        return view('nexus.auth.login');
    }

    /**
     * Handle a login attempt.
     * Rate limited to 5 attempts per minute per IP.
     */
    public function login(Request $request)
    {
        $request->validate([
            'email'    => ['required', 'email'],
            'password' => ['required'],
        ]);

        // Rate limiting — 5 attempts per minute per IP
        $key = 'nexus_login:' . $request->ip();

        if (RateLimiter::tooManyAttempts($key, 5)) {
            $seconds = RateLimiter::availableIn($key);
            return back()->withErrors([
                'email' => "Too many login attempts. Please wait {$seconds} seconds before trying again.",
            ])->withInput($request->only('email'));
        }

        $credentials = $request->only('email', 'password');
        $remember    = false;

        if (Auth::guard('nexus')->attempt($credentials, $remember)) {
            $admin = Auth::guard('nexus')->user();

            // Only role_id 1 (full admin) can access NEXUS
            if ($admin->role_id !== 1) {
                Auth::guard('nexus')->logout();
                $request->session()->invalidate();

                NexusAuditLogger::logLoginAttempt(
                    $request->email,
                    $request->ip(),
                    false
                );

                return back()->withErrors([
                    'email' => 'You do not have permission to access the NEXUS dashboard.',
                ])->withInput($request->only('email'));
            }

            // Clear rate limiter on successful login
            RateLimiter::clear($key);
            $request->session()->regenerate();

            NexusAuditLogger::logLoginAttempt(
                $request->email,
                $request->ip(),
                true,
                $admin->id
            );

            return redirect('/nexus/dashboard');
        }

        // Failed attempt
        RateLimiter::hit($key, 60);

        NexusAuditLogger::logLoginAttempt(
            $request->email,
            $request->ip(),
            false
        );

        return back()->withErrors([
            'email' => 'These credentials do not match our records.',
        ])->withInput($request->only('email'));
    }

    /**
     * Log out of the NEXUS dashboard.
     * Only clears the nexus guard session — main admin panel is unaffected.
     */
    public function logout(Request $request)
    {
        $admin = Auth::guard('nexus')->user();

        if ($admin) {
            NexusAuditLogger::logAdminAction(
                $admin->id,
                'admin_logout',
                'system',
                null,
                "Admin {$admin->name} logged out of NEXUS dashboard"
            );
        }

        Auth::guard('nexus')->logout();

        // Only invalidate the nexus-specific session data, not the entire session
        // (preserves main admin panel session if they are logged in there too)
        $request->session()->forget('nexus');

        return redirect()->route('nexus.login');
    }
}
