<?php
declare(strict_types=1);

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

final class PublisherCollection
{
    /** @var array<string, PublisherRecord> */
    private array $publishers = [];

    public static function fromArray(array $items): self
    {
        $collection = new self();

        foreach ($items as $item) {
            if (is_array($item)) {
                $record = PublisherRecord::fromArray($item);
                $collection->publishers[$record->publisherId()] = $record;
            }
        }

        return $collection;
    }

    public function record(string $publisherId, PublishResult $result): void
    {
        $this->publishers[$publisherId] ??= PublisherRecord::create($publisherId);
        $this->publishers[$publisherId] = $this->publishers[$publisherId]->record($result);
    }

    public function all(): array
    {
        return array_values($this->publishers);
    }

    public function count(): int
    {
        return count($this->publishers);
    }

    public function toArray(): array
    {
        return array_map(static fn (PublisherRecord $record): array => $record->toArray(), $this->all());
    }
}
