<?php
declare(strict_types=1);

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

final class PublishRequest
{
    public function __construct(
        private readonly string $publisherId,
        private readonly string $topic,
        private readonly string $type,
        private readonly array $payload = [],
        private readonly array $headers = [],
        private readonly int $priority = 0,
        private readonly int $delaySeconds = 0,
        private readonly string $createdAt = ''
    ) {}

    public static function create(
        string $publisherId,
        string $topic,
        string $type,
        array $payload = [],
        array $headers = [],
        int $priority = 0,
        int $delaySeconds = 0
    ): self {
        return new self($publisherId, $topic, $type, $payload, $headers, $priority, max(0, $delaySeconds), date('c'));
    }

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

    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 priority(): int { return $this->priority; }
    public function delaySeconds(): int { return $this->delaySeconds; }

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