<?php
declare(strict_types=1);

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

final class SagaStep
{
    public function __construct(
        private readonly string $stepId,
        private readonly string $commandType,
        private readonly string $aggregateType,
        private readonly array $payload = [],
        private readonly string $status = 'pending',
        private readonly string $createdAt = ''
    ) {}

    public static function create(string $stepId, string $commandType, string $aggregateType, array $payload = []): self
    {
        return new self($stepId, $commandType, $aggregateType, $payload, 'pending', date('c'));
    }

    public static function fromArray(array $data): self
    {
        return new self(
            (string) ($data['stepId'] ?? ''),
            (string) ($data['commandType'] ?? ''),
            (string) ($data['aggregateType'] ?? ''),
            (array) ($data['payload'] ?? []),
            (string) ($data['status'] ?? 'pending'),
            (string) ($data['createdAt'] ?? '')
        );
    }

    public function stepId(): string { return $this->stepId; }
    public function commandType(): string { return $this->commandType; }
    public function aggregateType(): string { return $this->aggregateType; }
    public function payload(): array { return $this->payload; }

    public function toArray(): array
    {
        return [
            'stepId' => $this->stepId,
            'commandType' => $this->commandType,
            'aggregateType' => $this->aggregateType,
            'payload' => $this->payload,
            'status' => $this->status,
            'createdAt' => $this->createdAt !== '' ? $this->createdAt : date('c'),
        ];
    }
}
