<?php
declare(strict_types=1);

namespace PpPhp\Core\Platform\Event\Distributed\Queue;

final class DistributedQueueRecord
{
    public const ACTIVE = 'active';
    public const PAUSED = 'paused';

    public function __construct(
        private readonly string $queueName,
        private readonly string $status = self::ACTIVE,
        private readonly int $priority = 0,
        private readonly int $pending = 0,
        private readonly int $reserved = 0,
        private readonly string $createdAt = '',
        private readonly string $updatedAt = ''
    ) {}

    public static function register(string $queueName, int $priority = 0): self
    {
        return new self($queueName, self::ACTIVE, $priority, 0, 0, date('c'), date('c'));
    }

    public static function fromArray(array $data): self
    {
        return new self(
            (string) ($data['queueName'] ?? ''),
            (string) ($data['status'] ?? self::ACTIVE),
            (int) ($data['priority'] ?? 0),
            (int) ($data['pending'] ?? 0),
            (int) ($data['reserved'] ?? 0),
            (string) ($data['createdAt'] ?? ''),
            (string) ($data['updatedAt'] ?? '')
        );
    }

    public function queueName(): string { return $this->queueName; }
    public function status(): string { return $this->status; }
    public function priority(): int { return $this->priority; }
    public function pending(): int { return max(0, $this->pending); }
    public function reserved(): int { return max(0, $this->reserved); }

    public function withCounters(int $pending, int $reserved = 0): self
    {
        return new self(
            $this->queueName,
            $this->status,
            $this->priority,
            max(0, $pending),
            max(0, $reserved),
            $this->createdAt,
            date('c')
        );
    }

    public function pause(): self
    {
        return new self($this->queueName, self::PAUSED, $this->priority, $this->pending(), $this->reserved(), $this->createdAt, date('c'));
    }

    public function resume(): self
    {
        return new self($this->queueName, self::ACTIVE, $this->priority, $this->pending(), $this->reserved(), $this->createdAt, date('c'));
    }

    public function toArray(): array
    {
        return [
            'queueName' => $this->queueName,
            'status' => $this->status,
            'priority' => $this->priority,
            'pending' => $this->pending(),
            'reserved' => $this->reserved(),
            'createdAt' => $this->createdAt !== '' ? $this->createdAt : date('c'),
            'updatedAt' => $this->updatedAt !== '' ? $this->updatedAt : date('c'),
        ];
    }
}
