<?php

declare(strict_types=1);

namespace Apexl\Tests\User\UnitTests;

use apexl\Config\ConfigurationMock;
use apexl\Io\modules\user\entities\userEntity;
use apexl\Io\modules\user\services\JwtCreator;
use apexl\Io\modules\user\services\TokenExpiryCalculator;
use apexl\Io\TestInfrastructure\UnitTest;
use Monolog\DateTimeImmutable;
use PHPUnit\Framework\Attributes\Test;
use function apexl\Io\container;

final class TokenExpiryCalculatorTest extends UnitTest
{
    #[Test]
    function fromNow(): void
    {
        $sessionId = $this->faker->uuid;
        $serverName = $this->faker->domainName();
        $issuedAt = DateTimeImmutable::createFromTimestamp(time());
        $secretKey = $this->faker->lexify(implode('?', array_fill(0, 512, '?')));
        $algorithm = $this->faker->randomElement([
            'HS256',
            'HS384',
            'HS512',
        ]);

        $lifetime = 1_000;

        $user = userEntity::factory()->create(['id' => $this->faker->numberBetween()], false);

        $config = new ConfigurationMock([
            'auth.jwt.secret_key' => $secretKey,
            'auth.jwt.algorithm' => $algorithm,
            'auth.jwt.lifetime' => $lifetime,
        ]);

        $jwt = container()->make(JwtCreator::class, [
            'config' => $config,
        ])->forUser($user, $sessionId, $issuedAt, $serverName);

        $expiresIn = container()->get(TokenExpiryCalculator::class)->fromNow($jwt, $issuedAt->getTimestamp());

        $this->assertSame($lifetime, $expiresIn);

        $expiresIn = container()->get(TokenExpiryCalculator::class)->fromNow($jwt, $issuedAt->getTimestamp() + 500);

        $this->assertSame($lifetime - 500, $expiresIn);
    }
}