<?php
declare(strict_types=1);

namespace PpPhp\Core\Platform\Workflow;

final class WorkflowRegistry
{
    /** @var array<string, WorkflowDefinition> */
    private array $definitions = [];

    public static function fromArray(array $items): self
    {
        $registry = new self();

        foreach ($items as $item) {
            if (is_array($item)) {
                $registry->register(WorkflowDefinition::fromArray($item));
            }
        }

        return $registry;
    }

    public function register(WorkflowDefinition $definition): WorkflowDefinition
    {
        $this->definitions[$definition->workflowId()] = $definition;
        return $definition;
    }

    public function get(string $workflowId): ?WorkflowDefinition
    {
        return $this->definitions[$workflowId] ?? null;
    }

    public function all(): array
    {
        return array_values($this->definitions);
    }

    public function count(): int
    {
        return count($this->definitions);
    }

    public function toArray(): array
    {
        return array_map(static fn (WorkflowDefinition $definition): array => $definition->toArray(), $this->all());
    }
}
