<?php
declare(strict_types=1);

namespace PpPhp\Core\Platform\Workflow\Engine;

final class WorkflowState
{
    public function __construct(
        private readonly string $stateId,
        private readonly string $instanceId,
        private readonly string $status = 'running',
        private readonly array $activeActivities = [],
        private readonly array $completedActivities = [],
        private readonly array $tokens = [],
        private readonly array $context = [],
        private readonly string $updatedAt = ''
    ) {}

    public static function start(string $instanceId, array $activeActivities = [], array $context = []): self
    {
        return new self(
            'workflow_state_' . substr(hash('sha256', $instanceId), 0, 24),
            $instanceId,
            'running',
            $activeActivities,
            [],
            array_map(static fn (string $id): string => 'token_' . substr(hash('sha256', $instanceId . $id), 0, 16), $activeActivities),
            $context,
            date('c')
        );
    }

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

    public function stateId(): string { return $this->stateId; }
    public function instanceId(): string { return $this->instanceId; }
    public function status(): string { return $this->status; }
    public function activeActivities(): array { return $this->activeActivities; }
    public function completedActivities(): array { return $this->completedActivities; }
    public function completed(): bool { return $this->status === 'completed'; }

    public function completeActivity(string $activityId, array $nextActivities = []): self
    {
        $active = array_values(array_filter($this->activeActivities, static fn ($id): bool => $id !== $activityId));
        foreach ($nextActivities as $next) {
            if ($next !== '' && !in_array($next, $active, true)) {
                $active[] = $next;
            }
        }

        $completed = $this->completedActivities;
        if (!in_array($activityId, $completed, true)) {
            $completed[] = $activityId;
        }

        $tokens = array_map(static fn (string $id): string => 'token_' . substr(hash('sha256', $id . date('c')), 0, 16), $active);

        return new self(
            $this->stateId,
            $this->instanceId,
            $active === [] ? 'completed' : 'running',
            $active,
            $completed,
            $tokens,
            $this->context,
            date('c')
        );
    }

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

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