<?php
declare(strict_types=1);

namespace PpPhp\Core\Platform\Workflow\Bpmn;

final class BpmnExporter
{
    public function export(BpmnModel $model): string
    {
        $xml = new \DOMDocument('1.0', 'UTF-8');
        $xml->formatOutput = true;

        $definitions = $xml->createElementNS('http://www.omg.org/spec/BPMN/20100524/MODEL', 'bpmn:definitions');
        $definitions->setAttribute('id', 'Definitions_' . $model->processId());
        $definitions->setAttribute('targetNamespace', 'https://ppphp.local/workflow/bpmn');
        $xml->appendChild($definitions);

        $process = $xml->createElement('bpmn:process');
        $process->setAttribute('id', $model->processId());
        $process->setAttribute('name', $model->name());
        $process->setAttribute('isExecutable', 'true');
        $definitions->appendChild($process);

        foreach ($model->elements() as $element) {
            $type = (string) ($element['type'] ?? 'task');
            $node = $xml->createElement('bpmn:' . $type);
            $node->setAttribute('id', (string) ($element['elementId'] ?? ''));
            if ((string) ($element['name'] ?? '') !== '') {
                $node->setAttribute('name', (string) $element['name']);
            }
            $process->appendChild($node);
        }

        foreach ($model->flows() as $flow) {
            $node = $xml->createElement('bpmn:sequenceFlow');
            $node->setAttribute('id', (string) ($flow['flowId'] ?? ''));
            $node->setAttribute('sourceRef', (string) ($flow['sourceRef'] ?? ''));
            $node->setAttribute('targetRef', (string) ($flow['targetRef'] ?? ''));
            if ((string) ($flow['name'] ?? '') !== '') {
                $node->setAttribute('name', (string) $flow['name']);
            }
            $process->appendChild($node);
        }

        return $xml->saveXML() ?: '';
    }
}
