<?php
declare(strict_types=1);

namespace PpPhp\Core\Platform\Event\Dispatcher\Validation;

use RuntimeException;
use PpPhp\Core\Platform\Event\Dispatcher\DelayedDispatcher;
use PpPhp\Core\Platform\Event\Queue\DeferredEvent;

final class DispatcherVerifier
{
    public function verify(): array
    {
        $dispatcher = new DelayedDispatcher();

        $success = $dispatcher->dispatch(DeferredEvent::fromEvent('dispatcher.success'), static function (): void {});

        $dispatcher->queue()->enqueue('dispatcher.queued');
        $queued = $dispatcher->dispatchQueued(static function (): void {});

        $dispatcher->scheduler()->dispatchLater('dispatcher.scheduled', 0);
        $scheduled = $dispatcher->dispatchScheduled(static function (): void {});

        $retry = $dispatcher->dispatch(DeferredEvent::fromEvent('dispatcher.retry'), static function (): void {
            throw new RuntimeException('transient dispatcher failure');
        });

        $dead = $dispatcher->dispatch(DeferredEvent::fromArray(['eventName' => 'dispatcher.dead', 'attempts' => 2]), static function (): void {
            throw new RuntimeException('dead dispatcher failure');
        });

        $snapshot = $dispatcher->snapshot()->toArray();
        $stats = $dispatcher->statistics()->toArray();

        $checks = [
            'directDispatch' => $success->ok(),
            'queuedDispatch' => $queued === 1,
            'scheduledDispatch' => $scheduled === 1,
            'retryHandling' => $retry->retried(),
            'deadLetterHandling' => $dead->deadLettered(),
            'statistics' => ($stats['executed'] ?? 0) >= 5 && ($stats['completed'] ?? 0) >= 3 && ($stats['failed'] ?? 0) >= 2,
            'snapshot' => isset($snapshot['queue'], $snapshot['scheduler'], $snapshot['retry'], $snapshot['statistics']),
            'pipeline' => count($dispatcher->pipeline()->stages()) >= 6,
        ];

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

        return [
            'ok' => !in_array(false, $checks, true),
            'checks' => $checks,
            'issues' => $issues,
            'summary' => [
                'executed' => $stats['executed'] ?? 0,
                'completed' => $stats['completed'] ?? 0,
                'retried' => $stats['retried'] ?? 0,
                'deadLettered' => $stats['deadLettered'] ?? 0,
                'failed' => $stats['failed'] ?? 0,
                'pipelineStages' => count($dispatcher->pipeline()->stages()),
                'score' => in_array(false, $checks, true) ? 80 : 100,
            ],
        ];
    }
}
