<?php
declare(strict_types=1);

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

final class StreamBroadcastDelivery
{
    public function __construct(private readonly string $deliveryId, private readonly string $broadcastId, private readonly string $subscriberId, private readonly string $topic, private readonly string $messageId = '', private readonly string $status = 'pending', private readonly string $reason = '', private readonly string $createdAt = '') {}

    public static function delivered(string $broadcastId, string $subscriberId, string $topic, string $messageId): self
    {
        return new self('delivery_' . substr(hash('sha256', $broadcastId . $subscriberId . $messageId), 0, 24), $broadcastId, $subscriberId, $topic, $messageId, 'delivered', 'broadcast delivered', date('c'));
    }

    public static function skipped(string $broadcastId, string $subscriberId, string $topic, string $reason): self
    {
        return new self('delivery_' . substr(hash('sha256', $broadcastId . $subscriberId . $reason), 0, 24), $broadcastId, $subscriberId, $topic, '', 'skipped', $reason, date('c'));
    }

    public static function fromArray(array $data): self
    {
        return new self((string) ($data['deliveryId'] ?? ''), (string) ($data['broadcastId'] ?? ''), (string) ($data['subscriberId'] ?? ''), (string) ($data['topic'] ?? ''), (string) ($data['messageId'] ?? ''), (string) ($data['status'] ?? 'pending'), (string) ($data['reason'] ?? ''), (string) ($data['createdAt'] ?? ''));
    }

    public function isDelivered(): bool { return $this->status === 'delivered'; }
    public function toArray(): array
    {
        return ['deliveryId' => $this->deliveryId, 'broadcastId' => $this->broadcastId, 'subscriberId' => $this->subscriberId, 'topic' => $this->topic, 'messageId' => $this->messageId, 'status' => $this->status, 'delivered' => $this->isDelivered(), 'reason' => $this->reason, 'createdAt' => $this->createdAt !== '' ? $this->createdAt : date('c')];
    }
}
