<?php
declare(strict_types=1);

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

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 QueueConsumerRuntimeSyncVerifier
{
    public function verify(string $basePath): array
    {
        $pool = WorkerPoolManager::resetInstance($basePath);
        $pool->clear();
        $pool->ensureDefaultPool(3);
        $pool->save();

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

        for ($i = 1; $i <= 3; $i++) {
            $first->consumer()->queue()->enqueue('consumer.sync.' . $i);
        }

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

        $second = QueueConsumerManager::resetInstance($basePath);
        $state = $second->consoleState();

        $stats = $state->statistics();
        $batchStats = $state->batchStatistics();
        $snapshot = $state->snapshot();

        $checks = [
            'batch' => $batch->acknowledged() === 3,
            'persistence' => $state->persisted(),
            'hydratedStats' => ($stats['consumed'] ?? 0) === 3 && ($stats['acknowledged'] ?? 0) === 3,
            'hydratedBatchStats' => ($batchStats['batches'] ?? 0) === 1 && ($batchStats['items'] ?? 0) === 3,
            'hydratedSnapshot' => isset($snapshot['statistics'], $snapshot['queue'], $snapshot['pool']),
            'singleton' => $second === QueueConsumerManager::instance($basePath),
        ];

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

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