<?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\HitlInterruptMessage;
use Drupal\flowdrop_interrupt\Message\InterruptMessageInterface;
use Drupal\flowdrop_interrupt\Service\InterruptFactoryInterface;
use Drupal\flowdrop_interrupt\Service\InterruptMessageHandlerInterface;

/**
 * Persists a {@see HitlInterruptMessage} as a FlowDropInterrupt entity.
 *
 * The handler always stamps {@see InterruptDirection::Outward} — a HITL
 * interrupt is always an outward prompt to the user (the direction passed
 * on the {@see ExecutionStamp} is ignored for this message shape).
 *
 * @internal
 */
final class HitlInterruptMessageHandler implements InterruptMessageHandlerInterface {

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

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

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

}
