<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Http\Requests\LoginRequest;
use App\Models\Organization;
use App\Services\AuthenticationService;
use App\Services\OtpService;
use Illuminate\Http\Request;
use Illuminate\Http\RedirectResponse;
use Illuminate\View\View;
use Illuminate\Support\Facades\Auth;

class LoginController extends Controller
{
    protected AuthenticationService $authService;
    protected OtpService $otpService;

    public function __construct(AuthenticationService $authService, OtpService $otpService)
    {
        $this->authService = $authService;
        $this->otpService = $otpService;
    }

    /**
     * Show the general login form.
     */
    public function showLoginForm(): View
    {
        $organization = Organization::first();
        return view('auth.login', [
            'role'         => null,
            'organization' => $organization,
        ]);
    }

    /**
     * Show role-specific login form.
     */
    public function showRoleLoginForm(string $role): View
    {
        $validRoles = [
            'members'        => 'Members',
            'trainers'       => 'Trainers',
            'trainees'       => 'Trainees',
            'mentor'         => 'Mentor',
            'mentee'         => 'Mentee',
            'partners'       => 'Partners',
            'contributor'    => 'Contributor',
            'health-marketor'=> 'Health Marketor',
        ];

        if (!isset($validRoles[$role])) {
            abort(404, 'Login page not found.');
        }

        $organization = Organization::first();

        return view('auth.login', [
            'role'         => $validRoles[$role],
            'roleSlug'     => $role,
            'organization' => $organization,
        ]);
    }

    /**
     * Handle a login request to the application.
     */
    public function login(LoginRequest $request): RedirectResponse
    {
        // Authenticate credentials (includes rate limiting via LoginRequest)
        $request->authenticate();
        $user = Auth::user();

        // Check if OTP is required
        if ($this->authService->requiresOtp($user)) {
            $this->otpService->generateAndSend($user);
            session(['auth.user_id' => $user->id, 'auth.remember' => $request->boolean('remember')]);
            Auth::logout();
            return redirect()->route('otp.verify')->with('status', 'A verification code has been sent to your email.');
        }

        // Check if 2FA is required
        if ($this->authService->requires2FA($user)) {
            session(['auth.user_id' => $user->id, 'auth.remember' => $request->boolean('remember')]);
            Auth::logout();
            return redirect()->route('two-factor.challenge');
        }

        // Complete authentication and redirect to role dashboard
        $this->authService->completeAuthentication($user, $request);

        // If there is a pending publication from the public submit form, handle it
        if (session('pending_publication')) {
            if ($user->can('create publications')) {
                // User has permission — create the draft immediately
                return redirect()->route('research.pending.create');
            }
            // User is logged in but lacks contributor permission — show a helpful notice
            return redirect()->route('research.public.submit.auth')
                ->with('warning', 'Your submission is saved, but your account type cannot submit publications. Please register as a Contributor to proceed.');
        }

        return redirect()->intended($user->getDashboardUrl());
    }

    /**
     * Log the user out of the application.
     */
    public function logout(Request $request): RedirectResponse
    {
        $this->authService->logout($request);

        return redirect()->route('login')->with('status', 'You have been logged out successfully.');
    }
}
