<?php
declare(strict_types=1);

namespace PpPhp\Core\Platform\Workflow;

final class WorkflowExecutionResult
{
    public function __construct(
        private readonly string $executionId,
        private readonly string $instanceId,
        private readonly string $activityId,
        private readonly bool $successful,
        private readonly string $message = '',
        private readonly string $createdAt = ''
    ) {}

    public static function success(WorkflowInstance $instance, WorkflowActivity $activity): self
    {
        return new self(
            'workflow_exec_' . substr(hash('sha256', $instance->instanceId() . $activity->activityId()), 0, 24),
            $instance->instanceId(),
            $activity->activityId(),
            true,
            'activity executed',
            date('c')
        );
    }

    public static function failed(WorkflowInstance $instance, string $activityId, string $message): self
    {
        return new self(
            'workflow_exec_' . substr(hash('sha256', $instance->instanceId() . $activityId . $message), 0, 24),
            $instance->instanceId(),
            $activityId,
            false,
            $message,
            date('c')
        );
    }

    public static function fromArray(array $data): self
    {
        return new self(
            (string) ($data['executionId'] ?? ''),
            (string) ($data['instanceId'] ?? ''),
            (string) ($data['activityId'] ?? ''),
            (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,
            'activityId' => $this->activityId,
            'successful' => $this->successful,
            'message' => $this->message,
            'createdAt' => $this->createdAt !== '' ? $this->createdAt : date('c'),
        ];
    }
}
