<?php

namespace Tests\Feature;

use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

class UserRecoveryCodesTest extends TestCase
{
    use RefreshDatabase;

    public function test_replace_generates_eight_unique_codes_and_persists(): void
    {
        $user = User::factory()->create();
        $codes = $user->replaceRecoveryCodes();

        $this->assertCount(8, $codes);
        $this->assertCount(8, array_unique($codes));
        $this->assertSame($codes, $user->fresh()->recoveryCodes());
        $this->assertTrue($user->fresh()->hasRecoveryCodes());
    }

    public function test_use_recovery_code_consumes_once(): void
    {
        $user = User::factory()->create();
        $codes = $user->replaceRecoveryCodes();
        $one = $codes[0];

        $this->assertTrue($user->useRecoveryCode(' '.$one.' ')); // trims
        $this->assertFalse($user->fresh()->useRecoveryCode($one)); // already consumed
        $this->assertFalse($user->fresh()->useRecoveryCode('not-a-code'));
        $this->assertCount(7, $user->fresh()->recoveryCodes());
    }
}
