<?php
declare(strict_types=1);

namespace PpPhp\Core\Platform\Workflow\Compensation;

final class WorkflowRollbackRequest
{
    public function __construct(
        private readonly string $requestId,
        private readonly string $workflowId,
        private readonly string $workflowInstanceId,
        private readonly array $completedActivityIds = [],
        private readonly string $reason = '',
        private readonly string $createdAt = ''
    ) {}

    public static function create(
        string $workflowId,
        string $workflowInstanceId,
        array $completedActivityIds = [],
        string $reason = 'workflow rollback requested'
    ): self {
        return new self(
            'workflow_rollback_' . substr(hash('sha256', $workflowId . $workflowInstanceId . json_encode($completedActivityIds)), 0, 24),
            $workflowId,
            $workflowInstanceId,
            $completedActivityIds,
            $reason,
            date('c')
        );
    }

    public static function fromArray(array $data): self
    {
        return new self(
            (string) ($data['requestId'] ?? ''),
            (string) ($data['workflowId'] ?? ''),
            (string) ($data['workflowInstanceId'] ?? ''),
            (array) ($data['completedActivityIds'] ?? []),
            (string) ($data['reason'] ?? ''),
            (string) ($data['createdAt'] ?? '')
        );
    }

    public function requestId(): string { return $this->requestId; }
    public function workflowId(): string { return $this->workflowId; }
    public function workflowInstanceId(): string { return $this->workflowInstanceId; }
    public function completedActivityIds(): array { return $this->completedActivityIds; }

    public function toArray(): array
    {
        return [
            'requestId' => $this->requestId,
            'workflowId' => $this->workflowId,
            'workflowInstanceId' => $this->workflowInstanceId,
            'completedActivityIds' => $this->completedActivityIds,
            'reason' => $this->reason,
            'createdAt' => $this->createdAt !== '' ? $this->createdAt : date('c'),
        ];
    }
}
