<?php
declare(strict_types=1);

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

final class DomainEventStatistics
{
    public static function from(array $listeners, array $envelopes, array $results, array $checkpoint): array
    {
        $dispatched = 0;
        $failed = 0;
        $totalTime = 0.0;

        foreach ($results as $result) {
            if (($result['successful'] ?? false) === true) {
                $dispatched++;
            } else {
                $failed++;
            }
            $totalTime += (float) ($result['dispatchTimeMs'] ?? 0);
        }

        return [
            'listeners' => count($listeners),
            'events' => count($envelopes),
            'results' => count($results),
            'dispatched' => $dispatched,
            'failed' => $failed,
            'lastSequence' => (int) ($checkpoint['lastSequence'] ?? 0),
            'processed' => (int) ($checkpoint['processed'] ?? 0),
            'averageDispatchTimeMs' => count($results) > 0 ? round($totalTime / count($results), 3) : 0,
            'throughput' => $totalTime > 0 ? round(($dispatched / max(0.001, $totalTime)) * 1000, 2) : 0,
        ];
    }
}
