<?php
declare(strict_types=1);

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

use PpPhp\Core\Platform\Event\Streaming\MessageBus;

final class MessageBusVerifier
{
    public function verify(string $basePath): array
    {
        $bus = MessageBus::resetInstance($basePath);
        $bus->clear();

        $topic = $bus->registerTopic('stream.default', 10);
        $envelope = $bus->publish('stream.default', 'stream.test', ['ok' => true], ['source' => 'verifier']);
        $delivered = $bus->deliver($envelope->message()->messageId());
        $bus->save();

        $second = MessageBus::resetInstance($basePath);
        $second->hydrate();

        $summary = $second->summary();
        $stats = $summary['statistics'];

        $checks = [
            'topic' => $topic->name() === 'stream.default',
            'publish' => ($stats['messages'] ?? 0) === 1,
            'deliver' => $delivered && ($stats['delivered'] ?? 0) === 1,
            'persistence' => $second->store()->exists(),
            'hydration' => count($summary['messages']) === 1,
        ];

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

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