<?php
declare(strict_types=1);

namespace PpPhp\Core\Platform\Event\Streaming;

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

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

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

    public function messageId(): string { return $this->messageId; }
    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 toArray(): array
    {
        return [
            'messageId' => $this->messageId,
            'topic' => $this->topic,
            'type' => $this->type,
            'payload' => $this->payload,
            'headers' => $this->headers,
            'createdAt' => $this->createdAt !== '' ? $this->createdAt : date('c'),
        ];
    }
}
