<?php
declare(strict_types=1);

namespace PpPhp\Core\Platform\Workflow\Bpmn;

final class BpmnDesignerModel
{
    public function __construct(
        private readonly string $designerId,
        private readonly string $processId,
        private readonly array $nodes = [],
        private readonly array $edges = [],
        private readonly string $createdAt = ''
    ) {}

    public static function fromBpmn(BpmnModel $model): self
    {
        $nodes = [];
        foreach ($model->elements() as $index => $element) {
            $nodes[] = [
                'id' => $element['elementId'] ?? '',
                'type' => $element['type'] ?? '',
                'label' => $element['name'] ?? $element['elementId'] ?? '',
                'x' => 120 + ($index * 180),
                'y' => 160,
            ];
        }

        $edges = [];
        foreach ($model->flows() as $flow) {
            $edges[] = [
                'id' => $flow['flowId'] ?? '',
                'source' => $flow['sourceRef'] ?? '',
                'target' => $flow['targetRef'] ?? '',
                'label' => $flow['name'] ?? '',
            ];
        }

        return new self(
            'bpmn_designer_' . substr(hash('sha256', $model->processId()), 0, 24),
            $model->processId(),
            $nodes,
            $edges,
            date('c')
        );
    }

    public static function fromArray(array $data): self
    {
        return new self(
            (string) ($data['designerId'] ?? ''),
            (string) ($data['processId'] ?? ''),
            (array) ($data['nodes'] ?? []),
            (array) ($data['edges'] ?? []),
            (string) ($data['createdAt'] ?? '')
        );
    }

    public function designerId(): string { return $this->designerId; }

    public function toArray(): array
    {
        return [
            'designerId' => $this->designerId,
            'processId' => $this->processId,
            'nodes' => $this->nodes,
            'edges' => $this->edges,
            'createdAt' => $this->createdAt !== '' ? $this->createdAt : date('c'),
        ];
    }
}
