<?php
declare(strict_types=1);

namespace PpPhp\Core\Platform\Workflow;

final class WorkflowInstance
{
    public function __construct(
        private readonly string $instanceId,
        private readonly string $workflowId,
        private readonly string $status = 'running',
        private readonly string $currentActivityId = '',
        private readonly array $completedActivities = [],
        private readonly array $context = [],
        private readonly string $startedAt = '',
        private readonly string $updatedAt = ''
    ) {}

    public static function start(WorkflowDefinition $definition, array $context = []): self
    {
        $first = $definition->firstActivity();

        return new self(
            'workflow_inst_' . substr(hash('sha256', $definition->workflowId() . json_encode($context) . microtime(true)), 0, 24),
            $definition->workflowId(),
            'running',
            $first?->activityId() ?? '',
            [],
            $context,
            date('c'),
            date('c')
        );
    }

    public static function fromArray(array $data): self
    {
        return new self(
            (string) ($data['instanceId'] ?? ''),
            (string) ($data['workflowId'] ?? ''),
            (string) ($data['status'] ?? 'running'),
            (string) ($data['currentActivityId'] ?? ''),
            (array) ($data['completedActivities'] ?? []),
            (array) ($data['context'] ?? []),
            (string) ($data['startedAt'] ?? ''),
            (string) ($data['updatedAt'] ?? '')
        );
    }

    public function instanceId(): string { return $this->instanceId; }
    public function workflowId(): string { return $this->workflowId; }
    public function status(): string { return $this->status; }
    public function currentActivityId(): string { return $this->currentActivityId; }
    public function isCompleted(): bool { return $this->status === 'completed'; }

    public function advance(string $completedActivityId, ?string $nextActivityId): self
    {
        $completed = $this->completedActivities;
        $completed[] = $completedActivityId;

        return new self(
            $this->instanceId,
            $this->workflowId,
            $nextActivityId === null || $nextActivityId === '' ? 'completed' : 'running',
            $nextActivityId ?? '',
            $completed,
            $this->context,
            $this->startedAt,
            date('c')
        );
    }

    public function fail(string $reason): self
    {
        return new self(
            $this->instanceId,
            $this->workflowId,
            'failed',
            $this->currentActivityId,
            $this->completedActivities,
            $this->context + ['failureReason' => $reason],
            $this->startedAt,
            date('c')
        );
    }

    public function toArray(): array
    {
        return [
            'instanceId' => $this->instanceId,
            'workflowId' => $this->workflowId,
            'status' => $this->status,
            'currentActivityId' => $this->currentActivityId,
            'completedActivities' => $this->completedActivities,
            'context' => $this->context,
            'startedAt' => $this->startedAt !== '' ? $this->startedAt : date('c'),
            'updatedAt' => $this->updatedAt !== '' ? $this->updatedAt : date('c'),
        ];
    }
}
