<?php

declare(strict_types=1);

namespace Drupal\flowdrop_node_processor\Plugin\FlowDropNodeProcessor;

use Drupal\flowdrop\Attribute\FlowDropNodeProcessor;
use Drupal\flowdrop\DTO\ParameterBagInterface;
use Drupal\flowdrop\DTO\ValidationResult;
use Drupal\flowdrop\Plugin\FlowDropNodeProcessor\AbstractFlowDropNodeProcessor;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Executor for Gateway/Branch nodes.
 *
 * Gateway nodes split execution paths based on conditions, allowing workflows
 * to branch into multiple execution paths. Similar to BPMN gateways.
 */
#[FlowDropNodeProcessor(
  id: "boolean_gateway",
  label: new \Drupal\Core\StringTranslation\TranslatableMarkup("Boolean Gateway"),
  description: "Split execution paths based on conditions for workflow branching",
  version: "1.0.0"
)]
class BooleanGateway extends AbstractFlowDropNodeProcessor {

  /**
   * {@inheritdoc}
   */
  public static function create(
    ContainerInterface $container,
    array $configuration,
    $plugin_id,
    $plugin_definition,
  ): static {
    return new static($configuration, $plugin_id, $plugin_definition);
  }

  /**
   * {@inheritdoc}
   */
  public function validateParams(array $params): ValidationResult {
    // Gateway nodes can accept any inputs or none.
    return ValidationResult::success();
  }

  /**
   * {@inheritdoc}
   */
  public function process(ParameterBagInterface $params): array {
    $inputValue = $params->get("value");
    $activeBranch = $inputValue ? "true" : "false";

    return [
      "active_branches" => $activeBranch,
      "input_value" => $inputValue,
      "execution_metadata" => [
        "timestamp" => time(),
        "gateway_type" => "branch",
        "flow_control" => TRUE,
      ],
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function getParameterSchema(): array {
    return [
      "type" => "object",
      "properties" => [
        "value" => [
          "type" => "boolean",
          "title" => "Input Value",
          "description" => "The value to evaluate against branch conditions",
          "required" => TRUE,
        ],
        "branches" => [
          "type" => "array",
          "description" => "The active branches",
          "default" => [
            [
              "name" => "True",
              "value" => TRUE,
            ],
            [
              "name" => "False",
              "value" => FALSE,
            ],
          ],
          "items" => [
            "type" => "object",
            "properties" => [
              "name" => [
                "type" => "string",
                "description" => "The name of the branch",
              ],
              "value" => [
                "type" => "boolean",
                "description" => "The value of the branch",
              ],
            ],
          ],
        ],
      ],
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function getOutputSchema(): array {
    return [];
  }

}
