<?php
declare(strict_types=1);

namespace PpPhp\Core\Platform\Workflow\Engine;

final class WorkflowEngineResult
{
    public function __construct(
        private readonly string $resultId,
        private readonly string $instanceId,
        private readonly string $activityId,
        private readonly array $activated = [],
        private readonly bool $successful = true,
        private readonly string $message = '',
        private readonly string $createdAt = ''
    ) {}

    public static function success(string $instanceId, string $activityId, array $activated = []): self
    {
        return new self(
            'workflow_engine_result_' . substr(hash('sha256', $instanceId . $activityId . json_encode($activated)), 0, 24),
            $instanceId,
            $activityId,
            $activated,
            true,
            'activity completed',
            date('c')
        );
    }

    public static function failed(string $instanceId, string $activityId, string $message): self
    {
        return new self(
            'workflow_engine_result_' . substr(hash('sha256', $instanceId . $activityId . $message), 0, 24),
            $instanceId,
            $activityId,
            [],
            false,
            $message,
            date('c')
        );
    }

    public static function fromArray(array $data): self
    {
        return new self(
            (string) ($data['resultId'] ?? ''),
            (string) ($data['instanceId'] ?? ''),
            (string) ($data['activityId'] ?? ''),
            (array) ($data['activated'] ?? []),
            (bool) ($data['successful'] ?? true),
            (string) ($data['message'] ?? ''),
            (string) ($data['createdAt'] ?? '')
        );
    }

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

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