<?php
declare(strict_types=1);

namespace PpPhp\Core\Platform\Workflow\Bpmn;

final class BpmnValidator
{
    public function validate(BpmnModel $model): array
    {
        $issues = [];
        $ids = [];

        foreach ($model->elements() as $element) {
            $id = (string) ($element['elementId'] ?? '');
            if ($id === '') {
                $issues[] = ['check' => 'elementId', 'message' => 'Element id missing.'];
                continue;
            }
            $ids[$id] = true;
        }

        if ($model->processId() === '') {
            $issues[] = ['check' => 'processId', 'message' => 'Process id missing.'];
        }

        if ($model->startElementId() === '') {
            $issues[] = ['check' => 'startEvent', 'message' => 'Start element missing.'];
        }

        foreach ($model->flows() as $flow) {
            $source = (string) ($flow['sourceRef'] ?? '');
            $target = (string) ($flow['targetRef'] ?? '');
            if (!isset($ids[$source])) {
                $issues[] = ['check' => 'flowSource', 'message' => 'Flow source missing: ' . $source];
            }
            if (!isset($ids[$target])) {
                $issues[] = ['check' => 'flowTarget', 'message' => 'Flow target missing: ' . $target];
            }
        }

        return [
            'ok' => $issues === [],
            'issues' => $issues,
            'elements' => count($model->elements()),
            'flows' => count($model->flows()),
        ];
    }
}
