<?php

declare(strict_types=1);

namespace Drupal\flowdrop_interrupt\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\Message\LinkedInterruptMessage;
use Drupal\flowdrop_interrupt\Service\InterruptFactoryInterface;
use Drupal\flowdrop_interrupt\Service\InterruptMessageHandlerInterface;

/**
 * Persists a {@see LinkedInterruptMessage} as a FlowDropInterrupt entity.
 *
 * The linkage lives on the typed `linked_interrupt_id` column — the cascade
 * subscriber resolves this interrupt with the linked interrupt's
 * response_data when the linked one resolves.
 *
 * @internal
 */
final class LinkedInterruptMessageHandler implements InterruptMessageHandlerInterface {

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

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

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

}
