<?php
declare(strict_types=1);

namespace PpPhp\Core\Platform\Event\Sourcing\EventStore\Validation;

use PpPhp\Core\Platform\Event\Sourcing\EventStore\EventStoreRuntime;

final class EventStoreVerifier
{
    public function verify(string $basePath): array
    {
        $runtime = EventStoreRuntime::resetInstance($basePath);
        $runtime->clear();

        $first = $runtime->append('order-1001', 'Order', 'OrderCreated', ['amount' => 100], ['source' => 'verifier']);
        $second = $runtime->append('order-1001', 'Order', 'OrderPaid', ['amount' => 100], ['source' => 'verifier']);
        $third = $runtime->append('customer-1', 'Customer', 'CustomerRegistered', ['name' => 'Test'], ['source' => 'verifier']);

        $runtime->save();

        $secondRuntime = EventStoreRuntime::resetInstance($basePath);
        $secondRuntime->hydrate();

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

        $checks = [
            'append' => $first->sequence() === 1 && $second->sequence() === 2 && $third->sequence() === 3,
            'aggregateVersion' => $first->aggregateVersion() === 1 && $second->aggregateVersion() === 2,
            'aggregateRead' => count($secondRuntime->eventsForAggregate('order-1001')) === 2,
            'typeRead' => count($secondRuntime->eventsForType('Order')) === 2,
            'statistics' => ($stats['events'] ?? 0) === 3 && ($stats['aggregates'] ?? 0) === 2,
            'persistence' => $secondRuntime->store()->exists(),
            'hydration' => count($summary['events']) === 3,
        ];

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

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