<?php
declare(strict_types=1);

namespace PpPhp\Core\Platform\Event\Streaming\Dlq;

final class StreamDlqStatistics
{
    public static function from(array $messages, array $results): array
    {
        $stats = [
            'messages' => count($messages),
            'dead' => 0,
            'retryPending' => 0,
            'retried' => 0,
            'replayed' => 0,
            'cleared' => 0,
            'results' => count($results),
            'successfulResults' => 0,
        ];

        foreach ($messages as $message) {
            $status = (string) ($message['status'] ?? StreamDlqStatus::DEAD);
            if ($status === StreamDlqStatus::DEAD) {
                $stats['dead']++;
            } elseif ($status === StreamDlqStatus::RETRY_PENDING) {
                $stats['retryPending']++;
            } elseif ($status === StreamDlqStatus::RETRIED) {
                $stats['retried']++;
            } elseif ($status === StreamDlqStatus::REPLAYED) {
                $stats['replayed']++;
            } elseif ($status === StreamDlqStatus::CLEARED) {
                $stats['cleared']++;
            }
        }

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

        return $stats;
    }
}
