<?php
declare(strict_types=1);

namespace PpPhp\Core\Platform\Workflow;

final class WorkflowDefinition
{
    public function __construct(
        private readonly string $workflowId,
        private readonly string $name,
        private readonly string $version = '1.0.0',
        private readonly array $activities = [],
        private readonly array $transitions = [],
        private readonly string $status = 'active',
        private readonly string $createdAt = ''
    ) {}

    public static function create(string $workflowId, string $name, array $activities = [], array $transitions = [], string $version = '1.0.0'): self
    {
        return new self($workflowId, $name, $version, $activities, $transitions, 'active', date('c'));
    }

    public static function fromArray(array $data): self
    {
        return new self(
            (string) ($data['workflowId'] ?? ''),
            (string) ($data['name'] ?? ''),
            (string) ($data['version'] ?? '1.0.0'),
            (array) ($data['activities'] ?? []),
            (array) ($data['transitions'] ?? []),
            (string) ($data['status'] ?? 'active'),
            (string) ($data['createdAt'] ?? '')
        );
    }

    public function workflowId(): string { return $this->workflowId; }
    public function name(): string { return $this->name; }
    public function version(): string { return $this->version; }
    public function activities(): array { return $this->activities; }
    public function transitions(): array { return $this->transitions; }
    public function isActive(): bool { return $this->status === 'active'; }

    public function firstActivity(): ?WorkflowActivity
    {
        $first = $this->activities[0] ?? null;
        return is_array($first) ? WorkflowActivity::fromArray($first) : null;
    }

    public function nextActivityId(string $activityId): ?string
    {
        foreach ($this->transitions as $transition) {
            if ((string) ($transition['from'] ?? '') === $activityId) {
                return (string) ($transition['to'] ?? '');
            }
        }

        return null;
    }

    public function activity(string $activityId): ?WorkflowActivity
    {
        foreach ($this->activities as $activity) {
            if ((string) ($activity['activityId'] ?? '') === $activityId) {
                return WorkflowActivity::fromArray((array) $activity);
            }
        }

        return null;
    }

    public function toArray(): array
    {
        return [
            'workflowId' => $this->workflowId,
            'name' => $this->name,
            'version' => $this->version,
            'activities' => $this->activities,
            'transitions' => $this->transitions,
            'status' => $this->status,
            'active' => $this->isActive(),
            'createdAt' => $this->createdAt !== '' ? $this->createdAt : date('c'),
        ];
    }
}
