<?php
declare(strict_types=1);

namespace PpPhp\Core\Platform\Workflow\Compensation;

final class WorkflowCompensationResult
{
    public function __construct(
        private readonly string $resultId,
        private readonly string $requestId,
        private readonly string $workflowInstanceId,
        private readonly string $activityId,
        private readonly string $compensationActivityId,
        private readonly bool $successful,
        private readonly string $message = '',
        private readonly string $createdAt = ''
    ) {}

    public static function success(WorkflowRollbackRequest $request, WorkflowCompensationAction $action): self
    {
        return new self(
            'workflow_comp_result_' . substr(hash('sha256', $request->requestId() . $action->actionId()), 0, 24),
            $request->requestId(),
            $request->workflowInstanceId(),
            $action->activityId(),
            $action->compensationActivityId(),
            true,
            'compensation executed',
            date('c')
        );
    }

    public static function failed(WorkflowRollbackRequest $request, string $activityId, string $message): self
    {
        return new self(
            'workflow_comp_result_' . substr(hash('sha256', $request->requestId() . $activityId . $message), 0, 24),
            $request->requestId(),
            $request->workflowInstanceId(),
            $activityId,
            '',
            false,
            $message,
            date('c')
        );
    }

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

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

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