<?php
declare(strict_types=1);

namespace PpPhp\Core\Platform\Event\Consumer\Hydration;

final class QueueConsumerStateMerger
{
    public function mergeStatistics(array $live, array $persisted): array
    {
        if (($live['consumed'] ?? 0) > 0 || $persisted === []) {
            return $this->normalizeStatistics($live);
        }

        return $this->normalizeStatistics($persisted);
    }

    public function mergeSnapshot(array $live, array $persisted): array
    {
        if (($live['statistics']['consumed'] ?? 0) > 0 || $persisted === []) {
            return $live;
        }

        return $persisted;
    }

    public function mergeBatchStatistics(array $live, array $persisted): array
    {
        if (($live['batches'] ?? 0) > 0 || $persisted === []) {
            return $this->normalizeBatchStatistics($live);
        }

        return $this->normalizeBatchStatistics($persisted);
    }

    private function normalizeStatistics(array $stats): array
    {
        return [
            'pending' => (int) ($stats['pending'] ?? 0),
            'consumed' => (int) ($stats['consumed'] ?? 0),
            'acknowledged' => (int) ($stats['acknowledged'] ?? 0),
            'failed' => (int) ($stats['failed'] ?? 0),
            'retried' => (int) ($stats['retried'] ?? 0),
            'deadLettered' => (int) ($stats['deadLettered'] ?? 0),
            'activeWorkers' => (int) ($stats['activeWorkers'] ?? 0),
            'dispatchTimeMs' => (float) ($stats['dispatchTimeMs'] ?? 0),
            'averageDispatchTimeMs' => (float) ($stats['averageDispatchTimeMs'] ?? 0),
            'throughput' => (float) ($stats['throughput'] ?? 0),
        ];
    }

    private function normalizeBatchStatistics(array $stats): array
    {
        return [
            'batches' => (int) ($stats['batches'] ?? 0),
            'items' => (int) ($stats['items'] ?? 0),
            'acknowledged' => (int) ($stats['acknowledged'] ?? 0),
            'failed' => (int) ($stats['failed'] ?? 0),
            'partial' => (int) ($stats['partial'] ?? 0),
            'successRate' => (float) ($stats['successRate'] ?? 0),
        ];
    }
}
