<?php
namespace Misuzu\Auth;

use Misuzu\Auth\SessionInfo;
use Misuzu\Users\UserInfo;

class AuthTokenBuilder {
    private array $props;
    private bool $edited = false;

    public function __construct(?AuthTokenInfo $baseTokenInfo = null) {
        $this->props = $baseTokenInfo === null ? [] : $baseTokenInfo->getProperties();
    }

    public function getProperties(): array {
        return $this->props;
    }

    public function setEdited(): void {
        $this->edited = true;
    }

    public function isEdited(): bool {
        return $this->edited;
    }

    public function setProperty(string $name, string $value): void {
        $this->props[$name] = $value;
    }

    public function removeProperty(string $name): void {
        $this->edited = true;
        unset($this->props[$name]);
    }

    public function setUserId(UserInfo|string $userId): void {
        if($userId instanceof UserInfo)
            $userId = $userId->getId();

        $this->setProperty(AuthTokenInfo::USER_ID, $userId);
    }

    public function removeUserId(): void {
        $this->removeProperty(AuthTokenInfo::USER_ID);
    }

    public function setSessionToken(SessionInfo|string $sessionKey): void {
        if($sessionKey instanceof SessionInfo)
            $sessionKey = $sessionKey->getToken();

        $this->setProperty(AuthTokenInfo::SESSION_TOKEN, $sessionKey);
    }

    public function removeSessionToken(): void {
        $this->removeProperty(AuthTokenInfo::SESSION_TOKEN);
    }

    public function setImpersonatedUserId(UserInfo|string $userId): void {
        if($userId instanceof UserInfo)
            $userId = $userId->getId();

        $this->setProperty(AuthTokenInfo::IMPERSONATED_USER_ID, $userId);
    }

    public function removeImpersonatedUserId(): void {
        $this->removeProperty(AuthTokenInfo::IMPERSONATED_USER_ID);
    }

    public function toInfo(?int $timestamp = null): AuthTokenInfo {
        return new AuthTokenInfo($timestamp ?? time(), $this->props);
    }
}
