<?php

declare(strict_types=1);

namespace Drupal\flowdrop_workflow_executor\Handler;

use Drupal\flowdrop_interrupt\DTO\ExecutionStamp;
use Drupal\flowdrop_interrupt\DTO\InterruptCreationData;
use Drupal\flowdrop_interrupt\Entity\FlowDropInterruptInterface;
use Drupal\flowdrop_interrupt\Enum\InterruptDirection;
use Drupal\flowdrop_interrupt\Message\InterruptMessageInterface;
use Drupal\flowdrop_interrupt\Service\InterruptFactoryInterface;
use Drupal\flowdrop_interrupt\Service\InterruptMessageHandlerInterface;
use Drupal\flowdrop_workflow_executor\Message\PipelineCompletionSentinelMessage;

/**
 * Persists a {@see PipelineCompletionSentinelMessage}.
 *
 * The handler maps the message's `subPipelineId` into the entity's
 * `pipelineId` column — that's the lookup key the completion subscriber
 * uses to match `PipelineCompletedEvent` (which carries the pipeline's
 * own id as `executionId`) against pending sentinels.
 *
 * @internal
 */
final class PipelineCompletionSentinelMessageHandler implements InterruptMessageHandlerInterface {

  public function __construct(
    private readonly InterruptFactoryInterface $factory,
  ) {}

  /**
   * {@inheritdoc}
   */
  public static function supports(): string {
    return PipelineCompletionSentinelMessage::class;
  }

  /**
   * {@inheritdoc}
   */
  public function handle(InterruptMessageInterface $message, ExecutionStamp $stamp): FlowDropInterruptInterface {
    assert($message instanceof PipelineCompletionSentinelMessage);
    return $this->factory->create(new InterruptCreationData(
      type: $message->getType(),
      workflowId: $stamp->workflowId,
      nodeId: $stamp->nodeId,
      message: $message->getMessage(),
      context: $message->getContext(),
      pipelineId: $message->subPipelineId,
      direction: InterruptDirection::Outward,
    ));
  }

}
