<?php
declare(strict_types=1);

namespace PpPhp\Core\Platform\Workflow\Compensation;

final class WorkflowCompensationAction
{
    public function __construct(
        private readonly string $actionId,
        private readonly string $workflowId,
        private readonly string $activityId,
        private readonly string $compensationActivityId,
        private readonly string $type = 'rollback',
        private readonly array $payload = [],
        private readonly string $createdAt = ''
    ) {}

    public static function create(
        string $workflowId,
        string $activityId,
        string $compensationActivityId,
        string $type = 'rollback',
        array $payload = []
    ): self {
        return new self(
            'workflow_comp_action_' . substr(hash('sha256', $workflowId . $activityId . $compensationActivityId), 0, 24),
            $workflowId,
            $activityId,
            $compensationActivityId,
            $type,
            $payload,
            date('c')
        );
    }

    public static function fromArray(array $data): self
    {
        return new self(
            (string) ($data['actionId'] ?? ''),
            (string) ($data['workflowId'] ?? ''),
            (string) ($data['activityId'] ?? ''),
            (string) ($data['compensationActivityId'] ?? ''),
            (string) ($data['type'] ?? 'rollback'),
            (array) ($data['payload'] ?? []),
            (string) ($data['createdAt'] ?? '')
        );
    }

    public function actionId(): string { return $this->actionId; }
    public function workflowId(): string { return $this->workflowId; }
    public function activityId(): string { return $this->activityId; }
    public function compensationActivityId(): string { return $this->compensationActivityId; }

    public function toArray(): array
    {
        return [
            'actionId' => $this->actionId,
            'workflowId' => $this->workflowId,
            'activityId' => $this->activityId,
            'compensationActivityId' => $this->compensationActivityId,
            'type' => $this->type,
            'payload' => $this->payload,
            'createdAt' => $this->createdAt !== '' ? $this->createdAt : date('c'),
        ];
    }
}
