<?php

namespace Tests\Feature;

use App\Livewire\Auth\TwoFactorChallenge;
use App\Models\User;
use App\Services\WebauthnService;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Livewire\Livewire;
use Tests\TestCase;

class TwoFactorWebauthnTest extends TestCase
{
    use RefreshDatabase;

    private function pending(): User
    {
        $user = User::factory()->create(['two_factor_secret' => 'x', 'two_factor_confirmed_at' => now()]);
        session()->put('2fa.user', $user->id);

        return $user;
    }

    public function test_verified_assertion_logs_in(): void
    {
        $user = $this->pending();
        $svc = $this->mock(WebauthnService::class);
        $svc->shouldReceive('available')->andReturn(true);
        $svc->shouldReceive('verifyAssertion')->andReturn(true);

        Livewire::test(TwoFactorChallenge::class)->call('verifyWebauthn', ['fake' => 'assertion']);

        $this->assertAuthenticatedAs($user);
    }

    public function test_failed_assertion_does_not_log_in(): void
    {
        $this->pending();
        $svc = $this->mock(WebauthnService::class);
        $svc->shouldReceive('available')->andReturn(true);
        $svc->shouldReceive('verifyAssertion')->andReturn(false);

        Livewire::test(TwoFactorChallenge::class)
            ->call('verifyWebauthn', ['fake' => 'assertion'])
            ->assertHasErrors('code');

        $this->assertGuest();
    }
}
