<?php
declare(strict_types=1);

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

final class StreamBroadcastResult
{
    public function __construct(private readonly string $broadcastId, private readonly string $topic, private readonly int $targets = 0, private readonly int $delivered = 0, private readonly int $skipped = 0, private readonly array $deliveries = [], private readonly float $broadcastTimeMs = 0.0, private readonly string $createdAt = '') {}

    public static function create(string $broadcastId, string $topic, array $deliveries, float $broadcastTimeMs): self
    {
        $delivered = 0; $skipped = 0;
        $rows = [];
        foreach ($deliveries as $delivery) {
            $row = $delivery instanceof StreamBroadcastDelivery ? $delivery->toArray() : (array) $delivery;
            $rows[] = $row;
            if (($row['delivered'] ?? false) === true) { $delivered++; } else { $skipped++; }
        }
        return new self($broadcastId, $topic, count($rows), $delivered, $skipped, $rows, $broadcastTimeMs, date('c'));
    }

    public static function fromArray(array $data): self
    {
        return new self((string) ($data['broadcastId'] ?? ''), (string) ($data['topic'] ?? ''), (int) ($data['targets'] ?? 0), (int) ($data['delivered'] ?? 0), (int) ($data['skipped'] ?? 0), (array) ($data['deliveries'] ?? []), (float) ($data['broadcastTimeMs'] ?? 0.0), (string) ($data['createdAt'] ?? ''));
    }

    public function broadcastId(): string { return $this->broadcastId; }
    public function delivered(): int { return $this->delivered; }
    public function skipped(): int { return $this->skipped; }
    public function targets(): int { return $this->targets; }

    public function toArray(): array
    {
        return ['broadcastId' => $this->broadcastId, 'topic' => $this->topic, 'targets' => $this->targets, 'delivered' => $this->delivered, 'skipped' => $this->skipped, 'deliveries' => $this->deliveries, 'broadcastTimeMs' => round($this->broadcastTimeMs, 3), 'createdAt' => $this->createdAt !== '' ? $this->createdAt : date('c')];
    }
}
