<?php
declare(strict_types=1);

namespace PpPhp\Core\Platform\Workflow\Timer\Validation;

use PpPhp\Core\Platform\Workflow\Timer\WorkflowTimer;
use PpPhp\Core\Platform\Workflow\Timer\WorkflowTimerRuntime;

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

        $due = $runtime->schedule(WorkflowTimer::dueNow('timer-workflow-1', 'send_reminder', ['reminder' => true]));
        $future = $runtime->schedule(WorkflowTimer::schedule('timer-workflow-2', 'wait_approval', 3600, ['wait' => true]));
        $cancelled = $runtime->cancel($future->timerId());
        $fired = $runtime->fireDue(time());
        $runtime->save();

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

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

        $checks = [
            'schedule' => $due->timerId() !== '' && $future->timerId() !== '',
            'fireDue' => $fired === 1,
            'cancel' => $cancelled === true,
            'statistics' => ($stats['timers'] ?? 0) === 2 && ($stats['fired'] ?? 0) === 1 && ($stats['cancelled'] ?? 0) === 1,
            'results' => ($stats['firedResults'] ?? 0) === 1,
            'persistence' => $second->store()->exists(),
            'hydration' => count($summary['timers']) === 2,
        ];

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

        return ['ok' => !in_array(false, $checks, true), 'checks' => $checks, 'issues' => $issues, 'summary' => ['timers' => $stats['timers'] ?? 0, 'scheduled' => $stats['scheduled'] ?? 0, 'fired' => $stats['fired'] ?? 0, 'cancelled' => $stats['cancelled'] ?? 0, 'score' => in_array(false, $checks, true) ? 80 : 100]];
    }
}
