<?php

namespace Tests\Feature;

use App\Livewire\Auth\TwoFactorChallenge;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Livewire\Livewire;
use PragmaRX\Google2FAQRCode\Google2FA;
use Tests\TestCase;

class TwoFactorChallengeRecoveryTest extends TestCase
{
    use RefreshDatabase;

    private function enrolledUser(): User
    {
        return User::factory()->create([
            'two_factor_secret' => (new Google2FA)->generateSecretKey(),
            'two_factor_confirmed_at' => now(),
        ]);
    }

    public function test_recovery_code_logs_in_and_is_consumed(): void
    {
        $user = $this->enrolledUser();
        $code = $user->replaceRecoveryCodes()[0];
        session()->put('2fa.user', $user->id);

        Livewire::test(TwoFactorChallenge::class)
            ->set('code', $code)
            ->call('verify');

        $this->assertAuthenticatedAs($user);
        $this->assertFalse($user->fresh()->useRecoveryCode($code)); // consumed
    }

    public function test_invalid_code_fails(): void
    {
        $user = $this->enrolledUser();
        $user->replaceRecoveryCodes();
        session()->put('2fa.user', $user->id);

        Livewire::test(TwoFactorChallenge::class)
            ->set('code', '000000')
            ->call('verify')
            ->assertHasErrors('code');

        $this->assertGuest();
    }
}
