<?php
declare(strict_types=1);

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

use PpPhp\Core\Platform\Event\Sourcing\EventStore\EventStoreRuntime;
use PpPhp\Core\Platform\Event\Sourcing\Projection\ProjectionDefinition;
use PpPhp\Core\Platform\Event\Sourcing\Projection\ProjectionRuntime;

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

        $eventStore->append('projection-order-1', 'Order', 'OrderCreated', ['status' => 'created', 'amount' => 100]);
        $eventStore->append('projection-order-1', 'Order', 'OrderPaid', ['status' => 'paid']);
        $eventStore->append('projection-customer-1', 'Customer', 'CustomerRegistered', ['name' => 'Ada']);

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

        $definition = $runtime->register(ProjectionDefinition::create('orders_read_model', 'Orders Read Model', ['Order'], []));
        $processed = $runtime->run('orders_read_model');
        $model = $runtime->readModel('orders_read_model');
        $checkpoint = $runtime->checkpoint('orders_read_model');
        $rebuild = $runtime->rebuild('orders_read_model');

        $runtime->save();

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

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

        $checks = [
            'register' => $definition->projectionId() === 'orders_read_model',
            'run' => $processed === 2,
            'readModel' => $model !== null && $model->count() === 1,
            'checkpoint' => $checkpoint !== null && $checkpoint->lastSequence() === 2,
            'rebuild' => $rebuild === 2,
            'statistics' => ($stats['projections'] ?? 0) === 1 && ($stats['rows'] ?? 0) === 1,
            'persistence' => $second->store()->exists(),
            'hydration' => count($summary['readModels']) === 1,
        ];

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

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