<?php

namespace App\Http\Controllers\Auth;

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

class AuthenticatedSessionController extends Controller
{
    public function create(SettingsService $settings): View|RedirectResponse
    {
        if (Auth::check()) {
            return redirect()->route('dashboard');
        }

        return view('auth.login', [
            'emergencyLockEnabled' => $settings->emergencyLockEnabled(),
        ]);
    }

    public function store(
        LoginRequest $request,
        SettingsService $settings,
        LoginHistoryService $loginHistory,
        AuditLogService $auditLog,
    ): RedirectResponse {
        if ($settings->emergencyLockEnabled()) {
            return back()
                ->withInput($request->only('email'))
                ->withErrors(['email' => 'Emergency lock mode is enabled. New logins are temporarily paused.']);
        }

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

        $user = $request->user();
        $loginHistory->record($user, $request->session()->getId(), $request->ip(), $request->userAgent());
        $auditLog->record('auth', 'login.success', 'Super admin signed in successfully.', null, $user);

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

    public function destroy(Request $request, AuditLogService $auditLog): RedirectResponse
    {
        if ($request->user()) {
            $auditLog->record('auth', 'logout', 'Super admin signed out.', null, $request->user());
        }

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

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

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