<?php
declare(strict_types=1);

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

final class CommandStatistics
{
    public static function from(array $handlers, array $commands, array $results): array
    {
        $handled = 0;
        $failed = 0;
        $totalTime = 0.0;

        foreach ($results as $result) {
            if (($result['successful'] ?? false) === true) {
                $handled++;
            } else {
                $failed++;
            }

            $totalTime += (float) ($result['dispatchTimeMs'] ?? 0);
        }

        return [
            'handlers' => count($handlers),
            'commands' => count($commands),
            'results' => count($results),
            'handled' => $handled,
            'failed' => $failed,
            'averageDispatchTimeMs' => count($results) > 0 ? round($totalTime / count($results), 3) : 0,
            'throughput' => $totalTime > 0 ? round(($handled / max(0.001, $totalTime)) * 1000, 2) : 0,
        ];
    }
}
