<?php
declare(strict_types=1);

namespace PpPhp\Core\Platform\Event\Sourcing\Compaction;

final class EventStreamOptimizer
{
    public function optimize(array $events): array
    {
        usort($events, static fn (array $a, array $b): int => ((int) ($a['sequence'] ?? 0)) <=> ((int) ($b['sequence'] ?? 0)));

        $deduped = [];
        $seen = [];

        foreach ($events as $event) {
            $eventId = (string) ($event['eventId'] ?? '');
            if ($eventId !== '' && isset($seen[$eventId])) {
                continue;
            }

            if ($eventId !== '') {
                $seen[$eventId] = true;
            }

            $deduped[] = $event;
        }

        return $deduped;
    }
}
