<?php
declare(strict_types=1);

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

final class SagaDefinition
{
    public function __construct(
        private readonly string $sagaId,
        private readonly string $name,
        private readonly string $startEventType,
        private readonly array $steps = [],
        private readonly string $status = 'active',
        private readonly string $createdAt = ''
    ) {}

    public static function create(string $sagaId, string $name, string $startEventType, array $steps = []): self
    {
        return new self($sagaId, $name, $startEventType, $steps, 'active', date('c'));
    }

    public static function fromArray(array $data): self
    {
        return new self(
            (string) ($data['sagaId'] ?? ''),
            (string) ($data['name'] ?? ''),
            (string) ($data['startEventType'] ?? ''),
            (array) ($data['steps'] ?? []),
            (string) ($data['status'] ?? 'active'),
            (string) ($data['createdAt'] ?? '')
        );
    }

    public function sagaId(): string { return $this->sagaId; }
    public function name(): string { return $this->name; }
    public function startEventType(): string { return $this->startEventType; }
    public function steps(): array { return $this->steps; }
    public function active(): bool { return $this->status === 'active'; }

    public function startsWith(string $eventType): bool
    {
        return $this->active() && $this->startEventType === $eventType;
    }

    public function toArray(): array
    {
        return [
            'sagaId' => $this->sagaId,
            'name' => $this->name,
            'startEventType' => $this->startEventType,
            'steps' => $this->steps,
            'status' => $this->status,
            'active' => $this->active(),
            'createdAt' => $this->createdAt !== '' ? $this->createdAt : date('c'),
        ];
    }
}
