<?php

namespace Tests\Feature;

use App\Livewire\Auth\ForgotPassword;
use App\Models\User;
use App\Models\WebauthnCredential;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Hash;
use Livewire\Livewire;
use Tests\TestCase;

class ForgotPasswordKeyOnlyTest extends TestCase
{
    use RefreshDatabase;

    public function test_key_only_user_resets_with_a_backup_code(): void
    {
        $user = User::factory()->create(['must_change_password' => false]);
        WebauthnCredential::create(['user_id' => $user->id, 'name' => 'k', 'credential_id' => 'cid', 'public_key' => '{}', 'sign_count' => 0]);
        $codes = $user->fresh()->replaceRecoveryCodes();

        Livewire::test(ForgotPassword::class)
            ->set('email', $user->email)
            ->set('code', $codes[0])
            ->set('password', 'brand-New-Pass-9')
            ->set('password_confirmation', 'brand-New-Pass-9')
            ->call('resetPassword')
            ->assertRedirect(route('login'));

        $this->assertTrue(Hash::check('brand-New-Pass-9', $user->fresh()->password));
    }
}
