<?php
declare(strict_types=1);

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

use PpPhp\Core\Platform\Event\Streaming\Topic\StreamTopicManager;

final class StreamTopicVerifier
{
    public function verify(string $basePath): array
    {
        $manager = StreamTopicManager::resetInstance($basePath);
        $manager->clear();

        $topic = $manager->create('topic.verify', 10, 3, ['owner' => 'verifier']);
        $paused = $manager->pause('topic.verify');
        $resumed = $manager->resume('topic.verify');
        $archived = $manager->archive('topic.verify');

        $manager->save();

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

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

        $checks = [
            'create' => $topic->topic() === 'topic.verify',
            'pause' => $paused,
            'resume' => $resumed,
            'archive' => $archived && ($stats['archived'] ?? 0) === 1,
            'partitions' => ($stats['partitions'] ?? 0) === 3,
            'persistence' => $second->store()->exists(),
            'hydration' => ($stats['topics'] ?? 0) === 1,
        ];

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

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