<?php

namespace Tests\Unit;

use App\Services\ApiAccess\ApiKeyGenerator;
use App\Services\ApiAccess\ApiKeyProvisioner;
use PHPUnit\Framework\TestCase;

/**
 * Local API key generation (app/Services/ApiAccess).
 *
 * Runs on the lightweight tests/bootstrap.php (no CI4 boot, no database).
 * The generator and provisioner take callbacks for "does this key exist?"
 * and "save this row", which is the same decision resolveApiKey() makes
 * before it writes Admin.api_keys.
 */
final class ApiKeyGeneratorTest extends TestCase
{
    public function testRandomKeyIsFortyLowercaseAlphanumericChars(): void
    {
        $generator = new ApiKeyGenerator();

        for ($i = 0; $i < 20; $i++) {
            $key = $generator->randomKey();
            $this->assertSame(ApiKeyGenerator::LENGTH, strlen($key));
            $this->assertSame(1, preg_match('/^[0-9a-z]{40}$/', $key));
        }
    }

    public function testGenerateRetriesWhileTheCandidateAlreadyExists(): void
    {
        $generator = new ApiKeyGenerator();
        $calls     = 0;
        $rejected  = null;

        $key = $generator->generate(function (string $candidate) use (&$calls, &$rejected): bool {
            $calls++;
            if ($calls === 1) {
                $rejected = $candidate;
                return true;
            }

            return $candidate === $rejected;
        });

        $this->assertSame(2, $calls);
        $this->assertNotSame($rejected, $key);
        $this->assertSame(1, preg_match('/^[0-9a-z]{40}$/', $key));
    }

    public function testResolveReturnsExistingKeyWithoutInserting(): void
    {
        $inserts = 0;
        $key     = (new ApiKeyProvisioner())->resolve(
            22223,
            function (int $userId): string {
                $this->assertSame(22223, $userId);
                return 'alreadyissuedkeyalreadyissuedkeyalready';
            },
            function (): bool {
                $this->fail('existence check should not run when a key is already stored');
            },
            function () use (&$inserts): bool {
                $inserts++;
                return true;
            }
        );

        $this->assertSame('alreadyissuedkeyalreadyissuedkeyalready', $key);
        $this->assertSame(0, $inserts);
    }

    public function testResolveInsertsOnlyWhenLookupIsEmpty(): void
    {
        $insertedUser = null;
        $insertedKey  = null;

        $key = (new ApiKeyProvisioner())->resolve(
            15525,
            function (): string {
                return '';
            },
            function (): bool {
                return false;
            },
            function (int $userId, string $candidate) use (&$insertedUser, &$insertedKey): bool {
                $insertedUser = $userId;
                $insertedKey  = $candidate;
                return true;
            }
        );

        $this->assertSame(15525, $insertedUser);
        $this->assertSame($key, $insertedKey);
        $this->assertSame(1, preg_match('/^[0-9a-z]{40}$/', $key));
    }

    public function testResolveReturnsEmptyWhenInsertFails(): void
    {
        $key = (new ApiKeyProvisioner())->resolve(
            15525,
            function (): string {
                return '';
            },
            function (): bool {
                return false;
            },
            function (): bool {
                return false;
            }
        );

        $this->assertSame('', $key);
    }
}
