<?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;

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

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

    public function authenticate(): void
    {
        $this->ensureIsNotRateLimited();

        $loginString = $this->input('email') ?? $this->input('nisn') ?? $this->input('nip');
        
        $password = $this->input('password');

        if (!$loginString) {
            throw ValidationException::withMessages([
                'email' => 'Mohon masukkan NISN, NIP, atau Email.',
            ]);
        }

        if (Auth::attempt(['nisn' => $loginString, 'password' => $password], $this->boolean('remember'))) {
            RateLimiter::clear($this->throttleKey());
            return; 
        }

        if (Auth::attempt(['nip' => $loginString, 'password' => $password], $this->boolean('remember'))) {
            RateLimiter::clear($this->throttleKey());
            return; 
        }

        if (Auth::attempt(['email' => $loginString, 'password' => $password], $this->boolean('remember'))) {
            RateLimiter::clear($this->throttleKey());
            return; 
        }

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

        $fieldError = $this->input('nisn') ? 'nisn' : ($this->input('nip') ? 'nip' : 'email');

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

    public function ensureIsNotRateLimited(): void
    {
        if (! RateLimiter::tooManyAttempts($this->throttleKey(), 5)) {
            return;
        }

        event(new Lockout($this));
        $seconds = RateLimiter::availableIn($this->throttleKey());

        throw ValidationException::withMessages([
            'email' => trans('auth.throttle', [
                'seconds' => $seconds,
                'minutes' => ceil($seconds / 60),
            ]),
        ]);
    }

    public function throttleKey(): string
    {
        $field = $this->input('email') ?? $this->input('nisn') ?? $this->input('nip') ?? 'unknown';
        return Str::transliterate(Str::lower($field).'|'.$this->ip());
    }
}