<?php

namespace App\Http\Requests\Auth;

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;
use App\Models\User; 

class LoginRequest extends FormRequest
{
    public function authorize(): bool
    {
        return true;
    }

    public function rules(): array
    {
        return [
            'mobile' => ['required', 'string'], 
            'password' => ['required', 'string'],
        ];
    }

    /**
     * ✅ بازگردانی شده به حالت ورود مستقیم
     */
    public function authenticate(): void
    {
        $this->ensureIsNotRateLimited();

        // ۱. چک کن کاربر غیرفعال نباشد
        $user = User::where('mobile', $this->string('mobile'))->first();
        if ($user && $user->status === 'inactive') {
            RateLimiter::hit($this->throttleKey());
            throw ValidationException::withMessages([
                'mobile' => 'حساب کاربری شما غیرفعال شده است.',
            ]);
        }

        // ۲. تلاش برای ورود
        if (! Auth::attempt($this->only('mobile', 'password'), $this->boolean('remember'))) {
            RateLimiter::hit($this->throttleKey());
            throw ValidationException::withMessages([
                'mobile' => trans('auth.failed'),
            ]);
        }

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

    // ... (متدهای ensureIsNotRateLimited و throttleKey بدون تغییر) ...
    public function ensureIsNotRateLimited(): void
    {
        if (! RateLimiter::tooManyAttempts($this->throttleKey(), 5)) {
            return;
        }
        event(new Lockout($this));
        $seconds = RateLimiter::availableIn($this->throttleKey());
        throw ValidationException::withMessages([
            'mobile' => trans('auth.throttle', [
                'seconds' => $seconds,
                'minutes' => ceil($seconds / 60),
            ]),
        ]);
    }
    public function throttleKey(): string
    {
        return Str::transliterate(Str::lower($this->string('mobile')).'|'.$this->ip());
    }
}