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

        $roleDariForm = $this->input('role');
        $loginIdentifier = $this->input('nisn') ?: $this->input('nip');
        $password = $this->input('password');

        $errorField = $this->filled('nisn') ? 'nisn' : 'nip';

        if (!Auth::attempt(['nomor_induk' => $loginIdentifier, 'password' => $password], $this->boolean('remember'))) {
            RateLimiter::hit($this->throttleKey());

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

        $user = Auth::user();

        // Cek jika role sesuai
        if ($user->role !== $roleDariForm) {
            Auth::logout();
            $this->session()->invalidate();
            $this->session()->regenerateToken();

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

            $actualRole = Str::title($user->role ?? 'Tidak Dikenal');
            throw ValidationException::withMessages([
                'forbidden' => "Akses ditolak. Akun ini terdaftar sebagai {$actualRole}.",
            ]);
        }

        // Cek jika akun di-banned
        if ($user->is_banned) {
            Auth::logout();
            $this->session()->invalidate();
            $this->session()->regenerateToken();

            throw ValidationException::withMessages([
                'forbidden' => "Akun Anda telah dinonaktifkan. Silakan hubungi admin.",
            ]);
        }

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

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