<?php

declare(strict_types=1);

namespace Drupal\flowdrop_trigger\Plugin\FlowDropNodeProcessor;

use Drupal\flowdrop\DTO\ExecutionContextDTO;
use Drupal\flowdrop\DTO\ParameterBagInterface;
use Drupal\flowdrop\DTO\ValidationResult;
use Drupal\flowdrop\Plugin\FlowDropNodeProcessor\AbstractFlowDropNodeProcessor;
use Drupal\flowdrop\Plugin\FlowDropNodeProcessor\ExecutionContextAwareInterface;
use Drupal\flowdrop\Plugin\FlowDropNodeProcessor\TriggerNodeProcessorInterface;

/**
 * Abstract base class for Trigger nodes.
 *
 * This class provides common functionality for all trigger types
 * and defines the contract that trigger implementations must follow.
 *
 * @internal This class is not part of the public API and may change without notice.
 */
abstract class AbstractTrigger extends AbstractFlowDropNodeProcessor implements ExecutionContextAwareInterface, TriggerNodeProcessorInterface {

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

  /**
   * {@inheritdoc}
   */
  #[\Override] public function setExecutionContext(ExecutionContextDTO $context): void {
    $this->executionContext = $context;
  }

  /**
   * {@inheritdoc}
   */
  public function process(ParameterBagInterface $params): array {
    // Return initial data if available.
    // When triggered by an event, only the triggering trigger node executes,
    // and it has access to the event data in the initial data context.
    $initial_data = $this->executionContext->getInitialData();
    return [
      'data' => $initial_data,
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function validateParams(array $params): ValidationResult {
    // Triggers can accept any inputs or none.
    // The validation is more about the trigger configuration than inputs.
    return ValidationResult::success();
  }

  /**
   * {@inheritdoc}
   */
  public function getOutputSchema(): array {
    return [
      "type" => "object",
      "properties" => [
        "data" => [
          "type" => "object",
          "description" => "The processed trigger data",
        ],
      ],
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function getParameterSchema(): array {
    return [
      "type" => "object",
      "properties" => [],
    ];
  }

}
