<?php

namespace apexl\Io\modules\user\entities;

use apexl\Config\Singleton as Config;
use apexl\entityCore\enums\Casts;
use apexl\entityCore\traits\hasCasts;
use apexl\Io\includes\Entity;
use apexl\Io\includes\System;
use apexl\Io\modules\user\entities\operators\refreshTokenOperator;
use DateTime;
use DateTimeImmutable;

/**
 * @property int $user_id
 * @property string $token
 * @property DateTimeImmutable $expiry
 *
 * @mixin refreshTokenOperator;
 */
class refreshTokenEntity extends Entity
{
    use hasCasts;

    public function __construct()
    {
        parent::__construct('refresh_tokens');
        $this->setOperator(new refreshTokenOperator('refresh_tokens', 'user_id'));
    }

    public static function newExpiryFrom(?int $now = null): DateTimeImmutable
    {
        $expiry = new DateTime();
        $lifetime = System::getRegisteredService(Config::class)->app->jwt->refresh_token_lifetime;
        $expiry->setTimestamp(($now ?? time()) + $lifetime);

        return DateTimeImmutable::createFromMutable($expiry);
    }

    public function casts(): array
    {
        return [
            'user_id' => Casts::INT,
            'expiry' => Casts::DATETIME_STAMP,
        ];
    }

    public function isExpired(): bool
    {
        return $this->expiry && $this->expiry < new DateTimeImmutable();
    }
}
