<?php

namespace App\Livewire\Auth;

use App\Contracts\AuthServiceInterface;
use App\DTO\LoginDTO;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\Str;
use Livewire\Component;

class Login extends Component
{
    public string $email = '';
    public string $password = '';
    public bool $remember = false;

    protected function rules(): array
    {
        return [
            'email' => ['required', 'string', 'email'],
            'password' => ['required', 'string'],
            'remember' => ['nullable', 'boolean'],
        ];
    }

    protected function messages(): array
    {
        return [
            'email.required' => 'Email wajib diisi.',
            'email.email' => 'Format email tidak valid.',
            'password.required' => 'Password wajib diisi.',
        ];
    }

    public function login(AuthServiceInterface $authService)
    {
        $this->validate();

        $throttleKey = Str::transliterate(Str::lower($this->email).'|'.request()->ip());

        // Rate Limiter: Maksimal 5 attempt per minute sesuai PRD Section 2
        if (RateLimiter::tooManyAttempts($throttleKey, 5)) {
            $seconds = RateLimiter::availableIn($throttleKey);
            $this->addError('email', "Terlalu banyak percobaan login. Silakan coba lagi dalam {$seconds} detik.");
            return;
        }

        try {
            $loginDTO = LoginDTO::fromArray([
                'email' => $this->email,
                'password' => $this->password,
                'remember' => $this->remember,
            ]);

            $authService->login($loginDTO);
            RateLimiter::clear($throttleKey);

            $user = auth()->user();
            if ($user && $user->force_password_change) {
                session()->flash('warning', 'Anda wajib mengubah password default sebelum mengakses sistem.');
                return redirect()->route('force-change-password');
            }

            session()->flash('success', 'Selamat datang kembali, '.$user->name);
            return redirect()->intended(route('dashboard'));

        } catch (\Illuminate\Validation\ValidationException $e) {
            RateLimiter::hit($throttleKey, 60);
            foreach ($e->errors() as $field => $messages) {
                foreach ($messages as $message) {
                    $this->addError($field, $message);
                }
            }
        }
    }

    public function render()
    {
        return view('livewire.auth.login')
            ->layout('components.layouts.guest');
    }
}
