<?php
declare(strict_types=1);

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

use RuntimeException;
use PpPhp\Core\Platform\Event\Consumer\Batch\QueueConsumerBatchOptions;
use PpPhp\Core\Platform\Event\Consumer\QueueConsumerManager;
use PpPhp\Core\Platform\Event\Worker\Pool\WorkerPoolManager;

final class QueueConsumerBatchVerifier
{
    public function verify(string $basePath): array
    {
        $pool = WorkerPoolManager::resetInstance($basePath);
        $pool->clear();
        $pool->ensureDefaultPool(3);
        $pool->save();

        $manager = QueueConsumerManager::resetInstance($basePath);
        $manager->clear();

        for ($i = 1; $i <= 5; $i++) {
            $manager->consumer()->queue()->enqueue('consumer.batch.' . $i);
        }

        $batch = $manager->consumer()->consumeBatchResult(QueueConsumerBatchOptions::limit(5), static function (): void {});
        $manager->save();

        $stats = $manager->consumer()->statistics()->toArray();
        $batchStats = $manager->consumer()->batchEngine()->statistics()->toArray();

        $checks = [
            'batchTotal' => $batch->total() === 5,
            'batchAcknowledged' => $batch->acknowledged() === 5,
            'batchOk' => $batch->ok(),
            'consumerStats' => ($stats['consumed'] ?? 0) === 5 && ($stats['acknowledged'] ?? 0) === 5,
            'batchStats' => ($batchStats['batches'] ?? 0) === 1 && ($batchStats['items'] ?? 0) === 5,
            'pending' => ($stats['pending'] ?? -1) === 0,
        ];

        $issues = [];
        foreach ($checks as $check => $ok) {
            if (!$ok) {
                $issues[] = ['check' => $check, 'message' => 'Queue batch consumer verification failed: ' . $check];
            }
        }

        return [
            'ok' => !in_array(false, $checks, true),
            'checks' => $checks,
            'issues' => $issues,
            'summary' => [
                'batches' => $batchStats['batches'] ?? 0,
                'items' => $batchStats['items'] ?? 0,
                'acknowledged' => $batchStats['acknowledged'] ?? 0,
                'failed' => $batchStats['failed'] ?? 0,
                'score' => in_array(false, $checks, true) ? 80 : 100,
            ],
        ];
    }
}
