<?php

namespace App\Http\Controllers\Auth;

use App\Events\Auth\UserLoginSuccess;
use App\Http\Controllers\Controller;
use App\Http\Requests\Auth\LoginRequest;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\View\View;

class AuthenticatedSessionController extends Controller
{
    /**
     * Display the login view.
     */
    public function create(): View
    {
        return view('auth.login');
    }

    /**
     * Handle an incoming authentication request.
     */
    public function store(LoginRequest $request): RedirectResponse
    {
        $request->validate([
            'email' => ['required', 'email'],
            'password' => ['required'],
        ]);

        $loginAttemptsEnabled = $request->loginAttemptsEnabled();
        $throttleKey = $request->throttleKey();
        $maxAttempts = $request->maxLoginAttempts();
        $lockSeconds = $request->loginLockSeconds();

        if ($loginAttemptsEnabled && RateLimiter::tooManyAttempts($throttleKey, $maxAttempts)) {
            $secondsRemaining = RateLimiter::availableIn($throttleKey);
            $minutesRemaining = max(1, (int) ceil($secondsRemaining / 60));
            $message = 'Too many login attempts. Please try again in ' . $minutesRemaining . ' minute' . ($minutesRemaining === 1 ? '' : 's') . '.';

            return back()->withErrors([
                'email' => $message,
            ])->onlyInput('email');
        }

        $email = $request->email;
        $password = $request->password;
        $remember = $request->boolean('remember');

        if (Auth::attempt(['email' => $email, 'password' => $password, 'status' => 1], $remember)) {
            $request->session()->regenerate();

            $user = auth()->user();

            event(new UserLoginSuccess($request, $user));

            if ($loginAttemptsEnabled) {
                RateLimiter::clear($throttleKey);
            }

            return redirect()->intended(route('home', absolute: false));
        }

        $errorMessage = 'The provided credentials do not match our records.';

        if ($loginAttemptsEnabled) {
            $attempts = RateLimiter::hit($throttleKey, $lockSeconds);
            $remainingAttempts = max($maxAttempts - $attempts, 0);

            if ($remainingAttempts === 0) {
                $secondsRemaining = RateLimiter::availableIn($throttleKey);
                $minutesRemaining = max(1, (int) ceil($secondsRemaining / 60));
                $errorMessage = 'Too many login attempts. Please try again in ' . $minutesRemaining . ' minute' . ($minutesRemaining === 1 ? '' : 's') . '.';
            } else {
                $attemptLabel = $remainingAttempts === 1 ? 'attempt' : 'attempts';
                $errorMessage .= ' You have ' . $remainingAttempts . ' ' . $attemptLabel . ' remaining.';
            }
        }

        return back()->withErrors([
            'email' => $errorMessage,
        ])->onlyInput('email');

        // $request->authenticate();

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

        // return redirect()->intended(route('dashboard', absolute: false));
    }

    /**
     * Destroy an authenticated session.
     */
    public function destroy(Request $request): RedirectResponse
    {
        Auth::guard('web')->logout();

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

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

        return redirect('/');
    }
}
