<?php
declare(strict_types=1);

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

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

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

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

        $manager->consumer()->queue()->enqueue('consumer.verify.one');
        $manager->consumer()->queue()->enqueue('consumer.verify.two');

        $one = $manager->consumer()->consume(static function (): void {});
        $batch = $manager->consumer()->consumeBatch(10, static function (): void {});
        $snapshot = $manager->save();

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

        $checks = [
            'singleConsume' => $one->acknowledged(),
            'batchConsume' => $batch === 1,
            'statistics' => ($stats['consumed'] ?? 0) === 2 && ($stats['acknowledged'] ?? 0) === 2,
            'pending' => ($stats['pending'] ?? -1) === 0,
            'snapshot' => isset($snapshot->toArray()['statistics'], $snapshot->toArray()['queue'], $snapshot->toArray()['pool']),
            'persistence' => $manager->store()->exists(),
        ];

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

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