<?php

namespace App\Http\Requests\Auth;

use App\Models\User;
use Illuminate\Auth\Events\Lockout;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;

class LoginRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     */
    public function authorize(): bool
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array<string, \Illuminate\Contracts\Validation\Rule|array|string>
     */
    public function rules(): array
    {
        return [
            'email' => ['required', 'string', 'email'],
            'password' => ['required', 'string'],
        ];
    }

    /**
     * Attempt to authenticate the request's credentials.
     *
     * @throws \Illuminate\Validation\ValidationException
     */
    public function authenticate(): void
    {
        $this->ensureIsNotRateLimited();

        $email = strtolower($this->string('email')->toString());
        $user = User::whereRaw('lower(email) = ?', [$email])->first();

        if (! Auth::attempt($this->only('email', 'password'), $this->boolean('remember'))) {
            $decaySeconds = (int) config('auth.login_decay_minutes', 15) * 60;
            RateLimiter::hit($this->throttleKey(), $decaySeconds);

            if ($user) {
                $this->recordFailedLogin($user);
                if ($user->failed_login_attempts >= (int) config('auth.login_disable_total_failures', 10)) {
                    $user->is_disabled = true;
                    $user->save();
                    RateLimiter::clear($this->throttleKey());

                    throw ValidationException::withMessages([
                        'email' => 'Your account has been disabled due to too many failed login attempts. Please contact an administrator.',
                    ]);
                }
            }

            throw ValidationException::withMessages([
                'email' => trans('auth.failed'),
            ]);
        }

        RateLimiter::clear($this->throttleKey());

        if ($user) {
            $user->failed_login_attempts = 0;
            $user->failed_login_first_at = null;
            $user->last_failed_login_at = null;
            $user->save();
        }
    }

    /**
     * Record a failed login for an existing user (escalation tracking).
     */
    protected function recordFailedLogin(User $user): void
    {
        $windowHours = (int) config('auth.login_disable_window_hours', 24);
        $windowStart = now()->subHours($windowHours);

        if ($user->failed_login_first_at === null || $user->failed_login_first_at < $windowStart) {
            $user->failed_login_attempts = 1;
            $user->failed_login_first_at = now();
        } else {
            $user->failed_login_attempts = $user->failed_login_attempts + 1;
        }

        $user->last_failed_login_at = now();
        $user->save();
    }

    /**
     * Ensure the login request is not rate limited.
     *
     * @throws \Illuminate\Validation\ValidationException
     */
    public function ensureIsNotRateLimited(): void
    {
        $maxAttempts = (int) config('auth.login_max_attempts', 5);

        if (! RateLimiter::tooManyAttempts($this->throttleKey(), $maxAttempts)) {
            return;
        }

        event(new Lockout($this));

        $seconds = RateLimiter::availableIn($this->throttleKey());
        $minutes = (int) ceil($seconds / 60);

        throw ValidationException::withMessages([
            'email' => "Too many login attempts. Please try again in {$minutes} minutes.",
        ]);
    }

    /**
     * Get the rate limiting throttle key for the request.
     */
    public function throttleKey(): string
    {
        return Str::transliterate(Str::lower($this->string('email')).'|'.$this->ip());
    }
}
