<?php

declare(strict_types=1);

namespace apexl\Io\modules\user\Factories;

use apexl\Io\modules\user\entities\RefreshToken;
use Exception;
use Random\RandomException;

final readonly class RefreshTokenFactory
{
    /**
     * @throws RandomException
     * @throws Exception
     */
    public function create(int $userId): RefreshToken
    {
        $refreshToken = bin2hex(random_bytes(20));

        $refreshTokenEntity = RefreshToken::find($userId) ?? new RefreshToken();
        $refreshTokenEntity->user_id = $userId;
        $refreshTokenEntity->token = $refreshToken;
        $refreshTokenEntity->expiry = RefreshToken::newExpiryFrom();
        $refreshTokenEntity->store();

        return $refreshTokenEntity;
    }

}
