<?php
declare(strict_types=1);

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

use PpPhp\Core\Platform\Event\Streaming\MessageBus;
use PpPhp\Core\Platform\Event\Streaming\Publisher\PublishRequest;
use PpPhp\Core\Platform\Event\Streaming\Publisher\PublisherManager;
use PpPhp\Core\Platform\Event\Streaming\Subscriber\StreamSubscriberRuntime;

final class StreamSubscriberVerifier
{
    public function verify(string $basePath): array
    {
        MessageBus::resetInstance($basePath)->clear();
        PublisherManager::resetInstance($basePath)->clear();

        $publisher = PublisherManager::instance($basePath);
        for ($i = 1; $i <= 5; $i++) {
            $publisher->publish(PublishRequest::create('subscriber.publisher', 'subscriber.topic', 'subscriber.event', ['i' => $i]));
        }

        $runtime = StreamSubscriberRuntime::resetInstance($basePath);
        $runtime->clear();

        $subscriber = $runtime->register('subscriber.verify', 'subscriber.topic');
        $result = $runtime->consume('subscriber.verify', 5, true);
        $ack = $runtime->acknowledge('subscriber.verify');
        $runtime->save();

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

        $summary = $second->summary();
        $stats = $summary['statistics'];
        $sub = $summary['subscribers'][0] ?? [];

        $checks = [
            'registration' => $subscriber->subscriberId() === 'subscriber.verify',
            'subscription' => ($sub['topic'] ?? '') === 'subscriber.topic',
            'consume' => $result->consumed() === 5,
            'acknowledgement' => $result->acknowledged() === 5 && $ack,
            'offsets' => ((int) ($sub['offset'] ?? 0)) === 5,
            'persistence' => $second->store()->exists(),
            'hydration' => ($stats['subscribers'] ?? 0) === 1,
        ];

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

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