<?php

namespace App\Livewire\Auth;

use App\Livewire\Concerns\CompletesTwoFactorChallenge;
use Illuminate\Validation\ValidationException;
use Livewire\Attributes\Layout;
use Livewire\Attributes\Validate;
use Livewire\Component;

#[Layout('layouts.auth')]
class TwoFactorBackup extends Component
{
    use CompletesTwoFactorChallenge;

    #[Validate('required|string')]
    public string $code = '';

    public function mount()
    {
        if (! session()->has('2fa.user')) {
            return $this->redirect(route('login'), navigate: true);
        }
    }

    public function verify()
    {
        $this->validate();

        $this->assertNotRateLimited();

        $user = $this->pendingUser();

        if (! $user || ! $user->hasTwoFactorEnabled()) {
            session()->forget(['2fa.user', '2fa.remember']);
            throw ValidationException::withMessages(['code' => __('auth.session_expired')]);
        }

        // Backup-only view: a one-time recovery code is the sole accepted credential (no TOTP).
        if (! $user->useRecoveryCode($this->code)) {
            $this->recordFailedAttempt('2fa');
            throw ValidationException::withMessages(['code' => __('auth.invalid_code')]);
        }

        $this->clearRateLimit();

        return $this->completeLogin($user);
    }

    public function render()
    {
        return view('livewire.auth.two-factor-backup')->title(__('auth.title_backup'));
    }
}
