<?php

declare(strict_types=1);

namespace App\Framework\Redis\ValueObjects;

use App\Framework\Core\ValueObjects\Duration;

final readonly class RedisTtl
{
    public function __construct(
        public int $seconds,
        public bool $isPersistent,
        public bool $isExpired
    ) {
    }

    public static function fromSeconds(int $seconds): self
    {
        return new self(
            seconds: $seconds,
            isPersistent: $seconds === -1,
            isExpired: $seconds === -2 || $seconds < 0
        );
    }

    public static function persistent(): self
    {
        return new self(
            seconds: -1,
            isPersistent: true,
            isExpired: false
        );
    }

    public static function expired(): self
    {
        return new self(
            seconds: -2,
            isPersistent: false,
            isExpired: true
        );
    }

    public function getDisplayValue(): string
    {
        if ($this->isExpired) {
            return 'Expired';
        }

        if ($this->isPersistent) {
            return 'Never';
        }

        $duration = $this->toDuration();

        return $duration ? $duration->toHumanReadable() : 'Unknown';
    }

    public function toDuration(): ?Duration
    {
        if ($this->isPersistent || $this->isExpired) {
            return null;
        }

        return Duration::fromSeconds($this->seconds);
    }

    public function isExpiringSoon(int $thresholdSeconds = 300): bool
    {
        return ! $this->isPersistent && ! $this->isExpired && $this->seconds <= $thresholdSeconds;
    }
}
