<?php
declare(strict_types=1);

namespace PpPhp\Core\Platform\Workflow\Compensation;

final class WorkflowCompensationPlan
{
    public function __construct(
        private readonly string $planId,
        private readonly string $workflowId,
        private readonly array $actions = [],
        private readonly string $status = 'active',
        private readonly string $createdAt = ''
    ) {}

    public static function create(string $workflowId, array $actions = []): self
    {
        return new self(
            'workflow_comp_plan_' . substr(hash('sha256', $workflowId), 0, 24),
            $workflowId,
            $actions,
            'active',
            date('c')
        );
    }

    public static function fromArray(array $data): self
    {
        return new self(
            (string) ($data['planId'] ?? ''),
            (string) ($data['workflowId'] ?? ''),
            (array) ($data['actions'] ?? []),
            (string) ($data['status'] ?? 'active'),
            (string) ($data['createdAt'] ?? '')
        );
    }

    public function planId(): string { return $this->planId; }
    public function workflowId(): string { return $this->workflowId; }
    public function active(): bool { return $this->status === 'active'; }

    /** @return WorkflowCompensationAction[] */
    public function actionsForCompleted(array $completedActivityIds): array
    {
        $actions = [];

        foreach (array_reverse($completedActivityIds) as $activityId) {
            foreach ($this->actions as $action) {
                if ((string) ($action['activityId'] ?? '') === (string) $activityId) {
                    $actions[] = WorkflowCompensationAction::fromArray((array) $action);
                }
            }
        }

        return $actions;
    }

    public function toArray(): array
    {
        return [
            'planId' => $this->planId,
            'workflowId' => $this->workflowId,
            'actions' => $this->actions,
            'status' => $this->status,
            'active' => $this->active(),
            'createdAt' => $this->createdAt !== '' ? $this->createdAt : date('c'),
        ];
    }
}
