<?php
declare(strict_types=1);

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

final class SagaExecutionResult
{
    public function __construct(
        private readonly string $executionId,
        private readonly string $instanceId,
        private readonly string $sagaId,
        private readonly string $stepId,
        private readonly string $commandType,
        private readonly bool $successful,
        private readonly string $message = '',
        private readonly string $createdAt = ''
    ) {}

    public static function success(SagaInstance $instance, SagaStep $step): self
    {
        return new self(
            'saga_exec_' . substr(hash('sha256', $instance->instanceId() . $step->stepId()), 0, 24),
            $instance->instanceId(),
            $instance->sagaId(),
            $step->stepId(),
            $step->commandType(),
            true,
            'saga step executed',
            date('c')
        );
    }

    public static function failed(SagaInstance $instance, SagaStep $step, string $message): self
    {
        return new self(
            'saga_exec_' . substr(hash('sha256', $instance->instanceId() . $step->stepId() . $message), 0, 24),
            $instance->instanceId(),
            $instance->sagaId(),
            $step->stepId(),
            $step->commandType(),
            false,
            $message,
            date('c')
        );
    }

    public static function fromArray(array $data): self
    {
        return new self(
            (string) ($data['executionId'] ?? ''),
            (string) ($data['instanceId'] ?? ''),
            (string) ($data['sagaId'] ?? ''),
            (string) ($data['stepId'] ?? ''),
            (string) ($data['commandType'] ?? ''),
            (bool) ($data['successful'] ?? false),
            (string) ($data['message'] ?? ''),
            (string) ($data['createdAt'] ?? '')
        );
    }

    public function successful(): bool { return $this->successful; }

    public function toArray(): array
    {
        return [
            'executionId' => $this->executionId,
            'instanceId' => $this->instanceId,
            'sagaId' => $this->sagaId,
            'stepId' => $this->stepId,
            'commandType' => $this->commandType,
            'successful' => $this->successful,
            'message' => $this->message,
            'createdAt' => $this->createdAt !== '' ? $this->createdAt : date('c'),
        ];
    }
}
