<?php

declare(strict_types=1);

namespace Drupal\flowdrop_memory\Plugin\FlowDropNodeProcessor;

use Drupal\flowdrop\DTO\ExecutionContextDTO;

/**
 * Provides scope ID resolution from the execution context.
 *
 * Used by the context-aware MemoryRead and MemoryWrite processors to
 * derive the scope ID automatically from the runtime execution context.
 *
 * Resolution rules:
 * - "workflow"  → $context->getWorkflowId()
 * - "pipeline"  → $context->getPipelineId()
 * - "execution" → $context->getExecutionId()
 * - "session"   → metadata 'session_id' [soft convention]
 * - "global"/'' → '' (no sub-scope needed)
 * - unknown     → '' (graceful fallback)
 *
 * @see \Drupal\flowdrop\Plugin\FlowDropNodeProcessor\ExecutionContextAwareInterface
 */
trait ScopeResolutionTrait {

  /**
   * The execution context injected by the runtime before process().
   *
   * @var \Drupal\flowdrop\DTO\ExecutionContextDTO|null
   */
  private ?ExecutionContextDTO $executionContext = NULL;

  /**
   * Sets the execution context.
   *
   * @param \Drupal\flowdrop\DTO\ExecutionContextDTO $context
   *   The execution context.
   */
  public function setExecutionContext(ExecutionContextDTO $context): void {
    $this->executionContext = $context;
  }

  /**
   * Resolves the scope ID to use for a memory operation.
   *
   * Derives the scope ID from the execution context based on the scope name.
   * If no context is available, an empty string is returned.
   *
   * @param string $scope
   *   The memory scope name.
   *
   * @return string
   *   The resolved scope ID.
   */
  protected function resolveScopeId(string $scope): string {
    if ($this->executionContext === NULL) {
      return '';
    }

    return match ($scope) {
      'workflow'  => $this->executionContext->getWorkflowId(),
      'pipeline'  => $this->executionContext->getPipelineId(),
      'execution' => $this->executionContext->getExecutionId(),
      'session'   => (string) $this->executionContext->getMetadataValue('session_id', ''),
      default     => '',
    };
  }

}
