<?php
declare(strict_types=1);

namespace PpPhp\Core\Platform\Event\Sourcing\Saga;

final class SagaInstance
{
    public function __construct(
        private readonly string $instanceId,
        private readonly string $sagaId,
        private readonly string $correlationId,
        private readonly string $status = 'running',
        private readonly int $currentStep = 0,
        private readonly array $completedSteps = [],
        private readonly array $context = [],
        private readonly string $startedAt = '',
        private readonly string $updatedAt = ''
    ) {}

    public static function start(SagaDefinition $definition, string $correlationId, array $context = []): self
    {
        return new self(
            'saga_inst_' . substr(hash('sha256', $definition->sagaId() . $correlationId), 0, 24),
            $definition->sagaId(),
            $correlationId,
            'running',
            0,
            [],
            $context,
            date('c'),
            date('c')
        );
    }

    public static function fromArray(array $data): self
    {
        return new self(
            (string) ($data['instanceId'] ?? ''),
            (string) ($data['sagaId'] ?? ''),
            (string) ($data['correlationId'] ?? ''),
            (string) ($data['status'] ?? 'running'),
            (int) ($data['currentStep'] ?? 0),
            (array) ($data['completedSteps'] ?? []),
            (array) ($data['context'] ?? []),
            (string) ($data['startedAt'] ?? ''),
            (string) ($data['updatedAt'] ?? '')
        );
    }

    public function instanceId(): string { return $this->instanceId; }
    public function sagaId(): string { return $this->sagaId; }
    public function correlationId(): string { return $this->correlationId; }
    public function status(): string { return $this->status; }
    public function currentStep(): int { return max(0, $this->currentStep); }
    public function completed(): bool { return $this->status === 'completed'; }

    public function advance(string $stepId, int $totalSteps): self
    {
        $completed = $this->completedSteps;
        $completed[] = $stepId;
        $next = $this->currentStep() + 1;
        $status = $next >= $totalSteps ? 'completed' : 'running';

        return new self(
            $this->instanceId,
            $this->sagaId,
            $this->correlationId,
            $status,
            $next,
            $completed,
            $this->context,
            $this->startedAt,
            date('c')
        );
    }

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

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