<?php
declare(strict_types=1);

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

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

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

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

        $single = $manager->publish(PublishRequest::create('publisher.verify', 'publisher.topic', 'publisher.single', ['id' => 1]));
        $batch = $manager->publishBatch([
            PublishRequest::create('publisher.verify', 'publisher.topic', 'publisher.batch', ['id' => 2]),
            PublishRequest::create('publisher.verify.other', 'publisher.topic', 'publisher.batch', ['id' => 3]),
        ]);
        $delayed = $manager->publish(PublishRequest::create('publisher.verify', 'publisher.topic', 'publisher.delayed', ['id' => 4], [], 1, 30));

        $manager->save();

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

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

        $checks = [
            'publish' => $single->published(),
            'batch' => count($batch) === 2 && $batch[0]->published() && $batch[1]->published(),
            'delay' => $delayed->published(),
            'statistics' => ($stats['published'] ?? 0) === 4 && ($stats['failed'] ?? 0) === 0,
            'persistence' => $second->store()->exists(),
            'hydration' => count($summary['results']) === 4,
        ];

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

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