<?php
declare(strict_types=1);

namespace PpPhp\Core\Platform\Event\Streaming;

final class MessageBusEnvelope
{
    public function __construct(
        private readonly MessageBusMessage $message,
        private readonly string $status = 'pending',
        private readonly int $deliveryAttempts = 0,
        private readonly string $publishedAt = '',
        private readonly string $deliveredAt = ''
    ) {}

    public static function publish(MessageBusMessage $message): self
    {
        return new self($message, 'published', 0, date('c'), '');
    }

    public static function fromArray(array $data): self
    {
        return new self(
            MessageBusMessage::fromArray((array) ($data['message'] ?? [])),
            (string) ($data['status'] ?? 'pending'),
            (int) ($data['deliveryAttempts'] ?? 0),
            (string) ($data['publishedAt'] ?? ''),
            (string) ($data['deliveredAt'] ?? '')
        );
    }

    public function message(): MessageBusMessage { return $this->message; }
    public function status(): string { return $this->status; }

    public function markDelivered(): self
    {
        return new self($this->message, 'delivered', $this->deliveryAttempts + 1, $this->publishedAt, date('c'));
    }

    public function toArray(): array
    {
        return [
            'message' => $this->message->toArray(),
            'status' => $this->status,
            'deliveryAttempts' => $this->deliveryAttempts,
            'publishedAt' => $this->publishedAt !== '' ? $this->publishedAt : date('c'),
            'deliveredAt' => $this->deliveredAt,
        ];
    }
}
