<?php

declare(strict_types=1);

namespace Drupal\flowdrop_workflow_executor\Plugin\InterruptHandler;

use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\flowdrop_interrupt\Attribute\FlowDropInterruptHandler;
use Drupal\flowdrop_interrupt\Entity\FlowDropInterruptInterface;
use Drupal\flowdrop_interrupt\Plugin\InterruptHandler\AbstractInterruptHandler;
use Drupal\flowdrop_pipeline\Constants\PipelineStatus;

/**
 * Handler for sub-workflow execution interrupts.
 *
 * Created by `WorkflowNode::dispatchAsync()` when a sub-workflow is
 * dispatched in `JobAsync` mode. Resolved by cascade: a PipelineCompletion
 * sentinel resolves first (driven by `PipelineCompletionSubscriber` on the
 * sub-pipeline's `PipelineCompletedEvent`) and the parent's
 * WorkflowExecution interrupt is then resolved by the generic
 * LinkedInterruptResolvedSubscriber via the typed `linked_interrupt_id`
 * column.
 *
 * Operational only — does NOT implement `HitlInterruptHandlerInterface`,
 * so it does not appear in the human interrupt inbox. The inbox filter
 * (`$plugin instanceof HitlInterruptHandlerInterface`) hides these from
 * users.
 *
 * Response payload shape:
 *   {status: 'completed'|'failed'|'paused', outputs: array,
 *   execution_time_us: int}
 *
 * @internal
 */
#[FlowDropInterruptHandler(
  id: 'workflow_execution',
  label: new TranslatableMarkup('Sub-workflow execution'),
  description: 'Parent workflow paused while a dispatched sub-workflow runs',
)]
final class WorkflowExecutionHandler extends AbstractInterruptHandler {

  /**
   * {@inheritdoc}
   */
  public function normalizeResponse(mixed $raw, FlowDropInterruptInterface $interrupt): mixed {
    if (!is_array($raw)) {
      return ['status' => PipelineStatus::FAILED, 'outputs' => [], 'execution_time_us' => 0];
    }
    return [
      'status' => (string) ($raw['status'] ?? PipelineStatus::FAILED),
      'outputs' => is_array($raw['outputs'] ?? NULL) ? $raw['outputs'] : [],
      'execution_time_us' => (int) ($raw['execution_time_us'] ?? 0),
    ];
  }

}
