<?php

declare(strict_types=1);

namespace apexl\Io\modules\user\services;

use apexl\Io\modules\user\entities\userEntity;
use DateTimeImmutable;
use Firebase\JWT\JWT;
use function apexl\Io\config;

final class JwtCreator
{
    public function forUser(
        userEntity $user,
        string $sessionId,
    ): string {

        $secretKey = config('auth.jwt.secret_key');
        $algorithm = config('auth.jwt.algorithm');
        $lifetime = config('auth.jwt.lifetime');

        $issuedAt = new DateTimeImmutable();
        $expire = $issuedAt->modify("+$lifetime seconds")->getTimestamp();
        $serverName = $_SERVER['SERVER_NAME'];

        $payload = [
            'userId' => $user->id,
            'sessionId' => $sessionId,
            'iat' => $issuedAt->getTimestamp(),
            'exp' => $expire,
            'nbf' => $issuedAt->getTimestamp(),
            'iss' => $serverName,
        ];

        return JWT::encode($payload, $secretKey, $algorithm);
    }

}