<?php
declare(strict_types=1);

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

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

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

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

        $created = $runtime->save('cart-1001', 'Cart', 'CartCreated', ['status' => 'open'], ['source' => 'verifier']);
        $itemAdded = $runtime->save('cart-1001', 'Cart', 'ItemAdded', ['items' => [['sku' => 'A1', 'qty' => 1]]], ['source' => 'verifier']);
        $secondAggregate = $runtime->save('cart-1002', 'Cart', 'CartCreated', ['status' => 'open'], ['source' => 'verifier']);

        $loaded = $runtime->load('cart-1001');
        $history = $runtime->history('cart-1001');

        $runtime->saveSnapshot([$loaded, $secondAggregate]);

        $secondRuntime = AggregateRepositoryRuntime::resetInstance($basePath);
        $summary = $secondRuntime->summary(['cart-1001', 'cart-1002']);
        $stats = $summary['statistics'];

        $checks = [
            'save' => $created->version() === 1 && $itemAdded->version() === 2,
            'load' => $loaded->aggregateId() === 'cart-1001' && $loaded->version() === 2,
            'state' => (($loaded->state()['status'] ?? '') === 'open') && isset($loaded->state()['items']),
            'history' => count($history) === 2,
            'exists' => $secondRuntime->exists('cart-1001') && !$secondRuntime->exists('missing-cart'),
            'statistics' => ($stats['aggregates'] ?? 0) === 2 && ($stats['events'] ?? 0) === 3,
            'persistence' => $secondRuntime->store()->exists(),
        ];

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

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