<?php

declare(strict_types=1);

/*
 * This file is part of the Ferienpass package.
 *
 * (c) Richard Henkenjohann <richard@ferienpass.online>
 *
 * For more information visit the project website <https://ferienpass.online>
 * or the documentation under <https://docs.ferienpass.online>.
 */

namespace Ferienpass\CoreBundle\Tests\Generator;

use Ferienpass\CoreBundle\Entity\ApiToken;
use Ferienpass\CoreBundle\Generator\ApiTokenGenerator;
use PHPUnit\Framework\TestCase;

final class ApiTokenGeneratorTest extends TestCase
{
    private ApiTokenGenerator $generator;

    protected function setUp(): void
    {
        $this->generator = new ApiTokenGenerator();
    }

    public function testGenerateReturnsStringWithPrefix(): void
    {
        $token = $this->generator->generate();

        self::assertStringStartsWith(ApiToken::PERSONAL_ACCESS_TOKEN_PREFIX, $token);
    }

    public function testGenerateContainsDotSeparator(): void
    {
        $token = $this->generator->generate();

        self::assertStringContainsString('.', $token);
    }

    public function testGenerateWithCustomPrefix(): void
    {
        $token = $this->generator->generate('custom_');

        self::assertStringStartsWith('custom_', $token);
    }

    public function testGenerateProducesDifferentTokensEachTime(): void
    {
        $token1 = $this->generator->generate();
        $token2 = $this->generator->generate();

        self::assertNotSame($token1, $token2);
    }

    public function testGeneratedTokenHasCorrectFormat(): void
    {
        $rawToken = $this->generator->generate();
        [$locatorPart, $secretPart] = explode('.', $rawToken, 2) + ['', ''];

        // Remove prefix
        $prefix = ApiToken::PERSONAL_ACCESS_TOKEN_PREFIX;
        $locator = str_starts_with($locatorPart, $prefix) ? substr($locatorPart, \strlen($prefix)) : $locatorPart;

        self::assertNotEmpty($locator);
        self::assertNotEmpty($secretPart);
    }
}
