<?php
declare(strict_types=1);

namespace PpPhp\Core\Platform\Workflow\Bpmn;

final class BpmnModel
{
    public function __construct(
        private readonly string $processId,
        private readonly string $name = '',
        private readonly array $elements = [],
        private readonly array $flows = [],
        private readonly string $source = 'designer',
        private readonly string $createdAt = ''
    ) {}

    public static function create(string $processId, string $name, array $elements = [], array $flows = [], string $source = 'designer'): self
    {
        return new self($processId, $name, $elements, $flows, $source, date('c'));
    }

    public static function fromArray(array $data): self
    {
        return new self(
            (string) ($data['processId'] ?? ''),
            (string) ($data['name'] ?? ''),
            (array) ($data['elements'] ?? []),
            (array) ($data['flows'] ?? []),
            (string) ($data['source'] ?? 'designer'),
            (string) ($data['createdAt'] ?? '')
        );
    }

    public function processId(): string { return $this->processId; }
    public function name(): string { return $this->name; }
    public function elements(): array { return $this->elements; }
    public function flows(): array { return $this->flows; }

    public function startElementId(): string
    {
        foreach ($this->elements as $element) {
            if (($element['type'] ?? '') === 'startEvent') {
                return (string) ($element['elementId'] ?? '');
            }
        }
        return (string) ($this->elements[0]['elementId'] ?? '');
    }

    public function toArray(): array
    {
        return [
            'processId' => $this->processId,
            'name' => $this->name,
            'elements' => $this->elements,
            'flows' => $this->flows,
            'source' => $this->source,
            'createdAt' => $this->createdAt !== '' ? $this->createdAt : date('c'),
        ];
    }
}
