<?php
declare(strict_types=1);

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

final class StreamBroadcastRequest
{
    public function __construct(
        private readonly string $broadcastId,
        private readonly string $publisherId,
        private readonly string $topic,
        private readonly string $type,
        private readonly array $payload = [],
        private readonly array $headers = [],
        private readonly array $targetSubscribers = [],
        private readonly string $createdAt = ''
    ) {}

    public static function create(string $publisherId, string $topic, string $type, array $payload = [], array $headers = [], array $targetSubscribers = []): self
    {
        return new self('broadcast_' . substr(hash('sha256', $publisherId . $topic . $type . json_encode($payload) . microtime(true)), 0, 24), $publisherId, $topic, $type, $payload, $headers, $targetSubscribers, date('c'));
    }

    public static function fromArray(array $data): self
    {
        return new self((string) ($data['broadcastId'] ?? ''), (string) ($data['publisherId'] ?? ''), (string) ($data['topic'] ?? ''), (string) ($data['type'] ?? ''), (array) ($data['payload'] ?? []), (array) ($data['headers'] ?? []), (array) ($data['targetSubscribers'] ?? []), (string) ($data['createdAt'] ?? ''));
    }

    public function broadcastId(): string { return $this->broadcastId; }
    public function publisherId(): string { return $this->publisherId; }
    public function topic(): string { return $this->topic; }
    public function type(): string { return $this->type; }
    public function payload(): array { return $this->payload; }
    public function headers(): array { return $this->headers; }
    public function targetSubscribers(): array { return $this->targetSubscribers; }

    public function toArray(): array
    {
        return ['broadcastId' => $this->broadcastId, 'publisherId' => $this->publisherId, 'topic' => $this->topic, 'type' => $this->type, 'payload' => $this->payload, 'headers' => $this->headers, 'targetSubscribers' => $this->targetSubscribers, 'createdAt' => $this->createdAt !== '' ? $this->createdAt : date('c')];
    }
}
