<?php

declare(strict_types=1);

namespace Drupal\Tests\flowdrop_node_processor\Kernel;

use Drupal\KernelTests\KernelTestBase;
use Drupal\flowdrop\Constants\ReservedName;
use Drupal\flowdrop_node_type\Controller\Api\NodesController;

/**
 * Integration coverage for the Stop terminal node's resolved metadata.
 *
 * A Stop node is a terminal (exit) node, but it is reached via the normal flow
 * — unlike a start node — so it must still get the reserved trigger INPUT port
 * injected. This pins that the real Stop plugin, wired as a node type, is not
 * mistaken for a start node.
 *
 * @group flowdrop_node_processor
 * @coversDefaultClass \Drupal\flowdrop_node_type\Service\NodeMetadataResolver
 */
class StopNodeMetadataTest extends KernelTestBase {

  /**
   * {@inheritdoc}
   */
  protected static $modules = [
    'system',
    'user',
    'flowdrop',
    'flowdrop_node_category',
    'flowdrop_node_type',
    'flowdrop_node_processor',
  ];

  /**
   * {@inheritdoc}
   */
  protected function setUp(): void {
    parent::setUp();
    $this->installEntitySchema('flowdrop_node_category');
    $this->installEntitySchema('flowdrop_node_type');
  }

  /**
   * The Stop node type gets a trigger INPUT port: it is reachable, not a start.
   *
   * @covers ::buildForNodeType
   */
  public function testStopNodeKeepsTriggerInput(): void {
    $this->container->get('entity_type.manager')
      ->getStorage('flowdrop_node_type')
      ->create([
        'id' => 'stop',
        'label' => 'Stop',
        'enabled' => TRUE,
        'executor_plugin' => 'flowdrop_node_processor:stop',
      ])->save();

    $controller = NodesController::create($this->container);
    $response = $controller->getNodeMetadata('stop');
    $this->assertSame(200, $response->getStatusCode(), (string) $response->getContent());

    $payload = json_decode((string) $response->getContent(), TRUE);
    $inputs = $payload['data']['metadata']['inputs'] ?? [];

    $triggerPorts = array_values(array_filter(
      $inputs,
      static fn (array $port): bool => ($port['id'] ?? '') === ReservedName::PORT_TRIGGER,
    ));
    $this->assertCount(1, $triggerPorts, json_encode($inputs));
    $this->assertSame('input', $triggerPorts[0]['type']);
  }

}
