<?php

declare(strict_types=1);

namespace Apexl\Tests\User\Helpers;

use apexl\Io\modules\user\entities\userEntity;
use apexl\Io\modules\user\services\twoFactorAuth\TwoFactorAuthService;
use RobThree\Auth\Providers\Qr\BaconQrCodeProvider;
use RobThree\Auth\TwoFactorAuth;
use function apexl\Io\container;

/**
 * Shared 2FA test helpers: create deterministic users and drive full enrolment.
 */
trait EnrolsTwoFactor
{
    protected function twoFactorService(): TwoFactorAuthService
    {
        return container()->get(TwoFactorAuthService::class);
    }

    protected function makeUser(array $attrs = []): userEntity
    {
        $user = userEntity::factory()->create([
            'email' => $this->faker->unique()->safeEmail(),
            'nfc_key' => $this->faker->unique()->uuid(),
            'two_factor_enabled' => false,
            ...$attrs,
        ]);
        $this->assertNotNull($user->id, 'harness produced a null-id user');

        return $user;
    }

    protected function totpCodeFor(string $secret): string
    {
        return new TwoFactorAuth(new BaconQrCodeProvider(4, '#fff', '#000', 'svg'), 'x')
            ->getCode($secret, time());
    }

    /** Fully enrol a user (begin + confirm). Returns the shared secret. */
    protected function enrolUser(userEntity $user): string
    {
        $setup = $this->twoFactorService()->beginSetup($user);
        $this->twoFactorService()->completeSetup($user, $this->totpCodeFor($setup->secret));

        return $setup->secret;
    }
}
