<?php
declare(strict_types=1);

namespace PpPhp\Core\Platform\Event\Queue;

final class DeferredEventCollection
{
    private array $events = [];

    public function __construct(array $events = [])
    {
        foreach ($events as $event) {
            if ($event instanceof DeferredEvent) {
                $this->events[$event->id()] = $event;
            }
        }
    }

    public function add(DeferredEvent $event): void { $this->events[$event->id()] = $event; }
    public function remove(string $id): bool
    {
        if (!isset($this->events[$id])) {
            return false;
        }
        unset($this->events[$id]);
        return true;
    }
    public function get(string $id): ?DeferredEvent { return $this->events[$id] ?? null; }
    public function first(): ?DeferredEvent { return array_values($this->events)[0] ?? null; }
    public function all(): array { return array_values($this->events); }
    public function count(): int { return count($this->events); }
    public function isEmpty(): bool { return $this->events === []; }

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