<?php
declare(strict_types=1);

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

final class StreamTopicPartition
{
    public function __construct(
        private readonly string $partitionId,
        private readonly string $topic,
        private readonly int $index = 0,
        private readonly string $owner = '',
        private readonly string $createdAt = ''
    ) {}

    public static function create(string $topic, int $index, string $owner = ''): self
    {
        return new self(
            'topic_partition_' . substr(hash('sha256', $topic . $index . $owner), 0, 20),
            $topic,
            max(0, $index),
            $owner,
            date('c')
        );
    }

    public static function fromArray(array $data): self
    {
        return new self(
            (string) ($data['partitionId'] ?? ''),
            (string) ($data['topic'] ?? ''),
            (int) ($data['index'] ?? 0),
            (string) ($data['owner'] ?? ''),
            (string) ($data['createdAt'] ?? '')
        );
    }

    public function partitionId(): string { return $this->partitionId; }
    public function topic(): string { return $this->topic; }

    public function toArray(): array
    {
        return [
            'partitionId' => $this->partitionId,
            'topic' => $this->topic,
            'index' => $this->index,
            'owner' => $this->owner,
            'createdAt' => $this->createdAt !== '' ? $this->createdAt : date('c'),
        ];
    }
}
