<?php

declare(strict_types=1);

namespace Drupal\flowdrop_runtime\Service\Orchestrator\Trait;

/**
 * Provides port name extraction logic for orchestrators.
 *
 * This trait extracts port names from handle strings used in workflow edges.
 * Handle strings follow the format: "{nodeId}-{direction}-{portName}"
 * For example: "node_1-output-message" or "node_2-input-data"
 *
 * @see \Drupal\flowdrop_runtime\Service\Orchestrator\InterruptHandlingTrait
 *
 * @internal This trait is not part of the public API and may change without notice.
 */
trait PortNameExtractionTrait {

  /**
   * Extracts the port name from a handle string.
   *
   * @param string $handle
   *   The handle string (e.g., "node_1-output-message").
   * @param string $direction
   *   The direction to look for ("output" or "input").
   *
   * @return string|null
   *   The port name (e.g., "message"), or NULL if parsing failed.
   */
  protected function extractPortName(string $handle, string $direction): ?string {
    if (empty($handle)) {
      return NULL;
    }

    $pattern = "/-" . $direction . "-/";
    $parts = preg_split($pattern, $handle, 2);

    if ($parts !== FALSE && count($parts) === 2) {
      return $parts[1];
    }

    return NULL;
  }

}
