<?php

namespace App\Livewire\Auth;

use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Log;
use Livewire\Component;

class Login extends Component
{
    public $email;

    public $password;

    public $remember = false;

    public $can_login = false;

    public $error;

    public $error_message = '';

    public $loading = false;

    public function updatedEmail($value)
    {
        $this->resetErrorBag();
        if (empty($value)) {
            $this->can_login = false;
            return;
        }

        if (validate_email($value)) {
            $this->email = $value;
            $this->can_login = true;
        } else {
            $this->addError('email', 'Entrez une adresse email valide');
            $this->can_login = false;
        }
    }

    public function login()
    {
        $this->loading = true;

        // Rate limiting: 5 attempts per minute per IP
        $key = 'login-attempts:' . request()->ip();
        if (RateLimiter::tooManyAttempts($key, 5)) {
            $seconds = RateLimiter::availableIn($key);
            $this->addError('login', "Trop de tentatives de connexion. Réessayez dans {$seconds} secondes.");
            $this->loading = false;
            return;
        }

        $validator = Validator::make(
            [
                'email' => $this->email,
                'password' => $this->password,
            ],
            [
                'email' => ['required', 'email'],
                'password' => ['required', 'string', 'min:8'],
            ],
        );

        if ($validator->fails()) {
            if ($validator->errors()->has('email')) {
                $this->addError('email', $validator->errors()->first('email'));
            } elseif ($validator->errors()->has('password')) {
                $this->addError('password', $validator->errors()->first('password'));
            }
            $this->loading = false;
            return;
        }


        // FIRST, TRY API LOGIN
        $response = loginUserUsingApi($this->email, $this->password);


        // IF API LOGIN FAILS, RETURN ERROR MESSAGE
        if (! $response['success'] && $response['status'] === 500) {
            $this->password = '';
            $this->addError('login', 'Une erreur est survenue lors de la connexion. Veuillez réessayer plus tard.');
            $this->loading = false;
            return;
        }

        if ($response['success']) {
            // Create or update user from API response
            $user = createOrUpdateUserFromApi($response['data'], $this->password);

            if (! $user->loginUser($this->remember)) {
                // Record failed attempt
                // RateLimiter::hit($key, 60);
                $this->addError('email', 'Erreur de connexion locale');
                $this->loading = false;

                return;
            }

            // Clear rate limiter on successful login
            RateLimiter::clear($key);
            $this->loading = false;
            $this->redirect(route('home'), true);

            return;
        } else {

            if ($response['status'] === 401) {

                // FALLBACK TO LOCAL LOGIN (when API login fails or is not available)
                $localResponse = loginUserLocally($this->email, $this->password);

                if (! $localResponse['success']) {
                    // Record failed attempt
                    RateLimiter::hit($key, 60);
                    Log::error($localResponse['message']);
                    $this->addError('login', "Aucune correspondance trouvée pour cette adresse email et mot de passe.");
                    $this->loading = false;
                    $this->password = '';
                    return;
                }

                // Clear rate limiter on successful login
                RateLimiter::clear($key);

                // IF LOCAL LOGIN SUCCEEDS, CHECK IF OTP VERIFICATION IS REQUIRED
                $this->loading = false;
                $this->redirect(route('home'));
            }
        }
    }

    public function render()
    {
        return view('livewire.auth.login');
    }
}
