<?php
declare(strict_types=1);

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

use PpPhp\Core\Platform\Event\Streaming\MessageBus;
use PpPhp\Core\Platform\Event\Streaming\Broadcast\StreamBroadcastRequest;
use PpPhp\Core\Platform\Event\Streaming\Broadcast\StreamBroadcastRuntime;
use PpPhp\Core\Platform\Event\Streaming\Publisher\PublisherManager;
use PpPhp\Core\Platform\Event\Streaming\Subscriber\StreamSubscriberRuntime;

final class StreamBroadcastVerifier
{
    public function verify(string $basePath): array
    {
        MessageBus::resetInstance($basePath)->clear();
        PublisherManager::resetInstance($basePath)->clear();
        $subscribers = StreamSubscriberRuntime::resetInstance($basePath); $subscribers->clear();
        $subscribers->register('broadcast.subscriber.1', 'broadcast.topic');
        $subscribers->register('broadcast.subscriber.2', 'broadcast.topic');
        $subscribers->register('broadcast.subscriber.other', 'other.topic');
        $runtime = StreamBroadcastRuntime::resetInstance($basePath); $runtime->clear();
        $result = $runtime->broadcast(StreamBroadcastRequest::create('broadcast.publisher', 'broadcast.topic', 'broadcast.event', ['ok' => true]));
        $targeted = $runtime->broadcast(StreamBroadcastRequest::create('broadcast.publisher', 'broadcast.topic', 'broadcast.targeted', ['targeted' => true], [], ['broadcast.subscriber.1']));
        $runtime->save();
        $second = StreamBroadcastRuntime::resetInstance($basePath); $second->hydrate();
        $summary = $second->summary(); $stats = $summary['statistics'];
        $checks = ['broadcast' => $result->delivered() === 2, 'fanOut' => $result->targets() === 2, 'targeted' => $targeted->delivered() === 1 && $targeted->targets() === 1, 'statistics' => ($stats['delivered'] ?? 0) === 3 && ($stats['skipped'] ?? 0) === 0, 'persistence' => $second->store()->exists(), 'hydration' => count($summary['results']) === 2];
        $issues = [];
        foreach ($checks as $check => $ok) { if (!$ok) { $issues[] = ['check' => $check, 'message' => 'Broadcast verification failed: ' . $check]; } }
        return ['ok' => !in_array(false, $checks, true), 'checks' => $checks, 'issues' => $issues, 'summary' => ['broadcasts' => $stats['broadcasts'] ?? 0, 'targets' => $stats['targets'] ?? 0, 'delivered' => $stats['delivered'] ?? 0, 'skipped' => $stats['skipped'] ?? 0, 'score' => in_array(false, $checks, true) ? 80 : 100]];
    }
}
