<?php
declare(strict_types=1);

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

final class SagaStatistics
{
    public static function from(array $definitions, array $instances, array $executions): array
    {
        $running = 0;
        $completed = 0;
        $failed = 0;
        $successfulExecutions = 0;

        foreach ($instances as $instance) {
            $status = (string) ($instance['status'] ?? 'running');
            if ($status === 'completed') {
                $completed++;
            } elseif ($status === 'failed') {
                $failed++;
            } else {
                $running++;
            }
        }

        foreach ($executions as $execution) {
            if (($execution['successful'] ?? false) === true) {
                $successfulExecutions++;
            }
        }

        return [
            'sagas' => count($definitions),
            'instances' => count($instances),
            'running' => $running,
            'completed' => $completed,
            'failed' => $failed,
            'executions' => count($executions),
            'successfulExecutions' => $successfulExecutions,
        ];
    }
}
