<?php

namespace App\Http\Requests\Auth;

use App\Models\Dealer;
use App\Models\User;
use Illuminate\Auth\Events\Lockout;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
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());
        $userQuery = User::whereRaw('lower(email) = ?', [$email]);

        // If this request is for a dealer-specific login route (/login/{code}),
        // scope the user lookup to that dealer.
        $dealerCode = $this->route('code');
        if (is_string($dealerCode) && $dealerCode !== '') {
            $dealerId = Dealer::query()
                ->where('code', $dealerCode)
                ->where('is_active', true)
                ->value('id');

            if ($dealerId) {
                $userQuery->where('dealer_id', $dealerId);
            } else {
                // Dealer code is invalid or inactive – treat as failed auth.
                throw ValidationException::withMessages([
                    'email' => trans('auth.failed'),
                ]);
            }
        }

        $user = $userQuery->first();

        $password = $this->string('password')->toString();

        if (!$user || !Hash::check($password, (string) $user->password)) {
            $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'),
            ]);
        }

        // Preserve existing disabled-account behavior (treat disabled users as failed auth).
        if ($user->is_disabled) {
            $decaySeconds = (int) config('auth.login_decay_minutes', 15) * 60;
            RateLimiter::hit($this->throttleKey(), $decaySeconds);
            RateLimiter::clear($this->throttleKey());

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

        // Enforce branch-based access at login time.
        // Users without a branch, or whose branch is inactive, may not sign in.
        if (! $user->branch_id) {
            throw ValidationException::withMessages([
                'email' => 'Your account is not currently allowed to sign in. Please contact your administrator.',
            ]);
        }

        $branch = \App\Models\Branch::withoutGlobalScopes()
            ->select(['id', 'is_active'])
            ->find($user->branch_id);

        if (! $branch || ! $branch->is_active) {
            throw ValidationException::withMessages([
                'email' => 'Your branch is inactive. Please contact your administrator.',
            ]);
        }

        Auth::login($user, $this->boolean('remember'));

        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());
    }
}
