<?php
namespace Misuzu\Auth;

use Index\DateTime;
use Index\Data\IDbResult;
use Index\Net\IPAddress;

class RecoveryTokenInfo {
    public const LIFETIME = 60 * 60;

    private string $userId;
    private string $remoteAddr;
    private int $created;
    private ?string $code;

    public function __construct(IDbResult $result) {
        $this->userId = (string)$result->getInteger(0);
        $this->remoteAddr = $result->getString(1);
        $this->created = $result->getInteger(2);
        $this->code = $result->isNull(3) ? null : $result->getString(3);
    }

    public function getUserId(): string {
        return $this->userId;
    }

    public function getRemoteAddressRaw(): string {
        return $this->remoteAddr;
    }

    public function getRemoteAddress(): IPAddress {
        return IPAddress::parse($this->remoteAddr);
    }

    public function getCreatedTime(): int {
        return $this->created;
    }

    public function getCreatedAt(): DateTime {
        return DateTime::fromUnixTimeSeconds($this->created);
    }

    public function getExpirationTime(): int {
        return $this->created + self::LIFETIME;
    }

    public function getExpirationAt(): bool {
        return DateTime::fromUnixTimeSeconds($this->created + self::LIFETIME);
    }

    public function hasExpired(): bool {
        return $this->getExpirationTime() <= time();
    }

    public function hasCode(): bool {
        return $this->code !== null;
    }

    public function getCode(): ?string {
        return $this->code;
    }

    public function isValid(): bool {
        return $this->hasCode() && !$this->hasExpired();
    }
}
