<?php

declare(strict_types=1);

namespace Drupal\Tests\flowdrop_workflow_executor\Unit\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\Enum\InterruptType;
use Drupal\flowdrop_interrupt\Service\InterruptFactoryInterface;
use Drupal\flowdrop_workflow_executor\Handler\PipelineCompletionSentinelMessageHandler;
use Drupal\flowdrop_workflow_executor\Message\PipelineCompletionSentinelMessage;
use Drupal\Tests\UnitTestCase;
use Prophecy\Argument;
use Prophecy\PhpUnit\ProphecyTrait;

/**
 * @coversDefaultClass \Drupal\flowdrop_workflow_executor\Handler\PipelineCompletionSentinelMessageHandler
 * @group flowdrop_workflow_executor
 */
class PipelineCompletionSentinelMessageHandlerTest extends UnitTestCase {

  use ProphecyTrait;

  /**
   * Tests that supports() returns the message class name.
   */
  public function testSupportsReturnsMessageClass(): void {
    $this->assertSame(
      PipelineCompletionSentinelMessage::class,
      PipelineCompletionSentinelMessageHandler::supports(),
    );
  }

  /**
   * Tests that handle maps subSessionId into the pipelineId column.
   */
  public function testHandleMapsSubSessionIdIntoPipelineIdColumn(): void {
    $entity = $this->prophesize(FlowDropInterruptInterface::class)->reveal();
    $factory = $this->prophesize(InterruptFactoryInterface::class);
    $factory->create(Argument::that(function (InterruptCreationData $data) {
      return $data->type === InterruptType::PipelineCompletion
        && $data->workflowId === 'wf'
        && $data->nodeId === 'workflow'
        && $data->message === 'Awaiting completion'
        // The lookup-key overload: subSessionId lands in pipelineId.
        && $data->pipelineId === 'sub-sess-123'
        && $data->direction === InterruptDirection::Outward
        && $data->context === ['sub_session_id' => 'sub-sess-123'];
    }))->shouldBeCalled()->willReturn($entity);

    $handler = new PipelineCompletionSentinelMessageHandler($factory->reveal());
    $handler->handle(
      new PipelineCompletionSentinelMessage(
        message: 'Awaiting completion',
        subPipelineId: 'sub-sess-123',
        context: ['sub_session_id' => 'sub-sess-123'],
      ),
      new ExecutionStamp(workflowId: 'wf', nodeId: 'workflow'),
    );
  }

}
