<?php
declare(strict_types=1);

namespace PpPhp\Core\Platform\Event\Streaming\Topic;

final class StreamTopicMetadata
{
    public function __construct(
        private readonly string $topic,
        private readonly string $status = StreamTopicStatus::ACTIVE,
        private readonly int $priority = 0,
        private readonly int $partitions = 1,
        private readonly array $headers = [],
        private readonly string $createdAt = '',
        private readonly string $updatedAt = ''
    ) {}

    public static function create(string $topic, int $priority = 0, int $partitions = 1, array $headers = []): self
    {
        return new self($topic, StreamTopicStatus::ACTIVE, $priority, max(1, $partitions), $headers, date('c'), date('c'));
    }

    public static function fromArray(array $data): self
    {
        return new self(
            (string) ($data['topic'] ?? ''),
            (string) ($data['status'] ?? StreamTopicStatus::ACTIVE),
            (int) ($data['priority'] ?? 0),
            (int) ($data['partitions'] ?? 1),
            (array) ($data['headers'] ?? []),
            (string) ($data['createdAt'] ?? ''),
            (string) ($data['updatedAt'] ?? '')
        );
    }

    public function topic(): string { return $this->topic; }
    public function status(): string { return $this->status; }
    public function active(): bool { return $this->status === StreamTopicStatus::ACTIVE; }
    public function paused(): bool { return $this->status === StreamTopicStatus::PAUSED; }
    public function archived(): bool { return $this->status === StreamTopicStatus::ARCHIVED; }

    public function pause(): self
    {
        return new self($this->topic, StreamTopicStatus::PAUSED, $this->priority, $this->partitions, $this->headers, $this->createdAt, date('c'));
    }

    public function resume(): self
    {
        return new self($this->topic, StreamTopicStatus::ACTIVE, $this->priority, $this->partitions, $this->headers, $this->createdAt, date('c'));
    }

    public function archive(): self
    {
        return new self($this->topic, StreamTopicStatus::ARCHIVED, $this->priority, $this->partitions, $this->headers, $this->createdAt, date('c'));
    }

    public function toArray(): array
    {
        return [
            'topic' => $this->topic,
            'status' => $this->status,
            'active' => $this->active(),
            'paused' => $this->paused(),
            'archived' => $this->archived(),
            'priority' => $this->priority,
            'partitions' => max(1, $this->partitions),
            'headers' => $this->headers,
            'createdAt' => $this->createdAt !== '' ? $this->createdAt : date('c'),
            'updatedAt' => $this->updatedAt !== '' ? $this->updatedAt : date('c'),
        ];
    }
}
