<?php
declare(strict_types=1);

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

use PpPhp\Core\Platform\Workflow\Compensation\WorkflowCompensationAction;
use PpPhp\Core\Platform\Workflow\Compensation\WorkflowCompensationPlan;
use PpPhp\Core\Platform\Workflow\Compensation\WorkflowCompensationRuntime;
use PpPhp\Core\Platform\Workflow\Compensation\WorkflowRollbackRequest;

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

        $plan = $runtime->registerPlan(WorkflowCompensationPlan::create('order_workflow', [
            WorkflowCompensationAction::create('order_workflow', 'reserve_inventory', 'release_inventory')->toArray(),
            WorkflowCompensationAction::create('order_workflow', 'charge_payment', 'refund_payment')->toArray(),
            WorkflowCompensationAction::create('order_workflow', 'create_shipment', 'cancel_shipment')->toArray(),
        ]));

        $request = WorkflowRollbackRequest::create(
            'order_workflow',
            'order-workflow-inst-1',
            ['reserve_inventory', 'charge_payment', 'create_shipment'],
            'shipment failed'
        );

        $executed = $runtime->rollback($request);
        $runtime->save();

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

        $summary = $second->summary();
        $stats = $summary['statistics'];
        $firstResult = $summary['results'][0] ?? [];

        $checks = [
            'plan' => $plan->planId() !== '',
            'request' => $request->requestId() !== '',
            'rollback' => $executed === 3,
            'reverseOrder' => (($firstResult['activityId'] ?? '') === 'create_shipment'),
            'statistics' => ($stats['plans'] ?? 0) === 1 && ($stats['results'] ?? 0) === 3 && ($stats['successfulResults'] ?? 0) === 3,
            'persistence' => $second->store()->exists(),
            'hydration' => count($summary['requests']) === 1 && count($summary['results']) === 3,
        ];

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

        return [
            'ok' => !in_array(false, $checks, true),
            'checks' => $checks,
            'issues' => $issues,
            'summary' => [
                'plans' => $stats['plans'] ?? 0,
                'actions' => $stats['actions'] ?? 0,
                'requests' => $stats['requests'] ?? 0,
                'results' => $stats['results'] ?? 0,
                'score' => in_array(false, $checks, true) ? 80 : 100,
            ],
        ];
    }
}
