<?php

declare(strict_types=1);

namespace Drupal\flowdrop_node_processor\Plugin\FlowDropNodeProcessor;

use Drupal\Component\Serialization\Json;
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 Text Output nodes.
 */
#[FlowDropNodeProcessor(
  id: "text_output",
  label: new \Drupal\Core\StringTranslation\TranslatableMarkup("Text Output"),
  description: "Basic text output",
  version: "1.0.0"
)]
class TextOutput 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 {
    // Text output nodes can accept any inputs.
    return ValidationResult::success();
  }

  /**
   * {@inheritdoc}
   */
  protected function process(ParameterBagInterface $params): array {
    $text = "";

    $textParam = $params->get("text");
    if ($textParam !== NULL && $textParam !== "") {
      $text = $textParam;
    }

    // Convert array to string if necessary.
    if (is_array($text) || is_object($text)) {
      $text = JSON::encode($text);
    }

    // Ensure text is a string.
    $text = (string) $text;

    // Apply max length if configured.
    $maxLength = $params->get("maxLength", 1000);
    if (strlen($text) > $maxLength) {
      $text = substr($text, 0, $maxLength) . "...";
    }

    return [
      "output" => $text,
      "length" => strlen($text),
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function getParameterSchema(): array {
    return [
      "type" => "object",
      "properties" => [
        "text" => [
          "type" => "string",
          "title" => "Text Input",
          "description" => "The text to output",
          "required" => FALSE,
        ],
        "maxLength" => [
          "type" => "integer",
          "title" => "Maximum Length",
          "description" => "Maximum length of output text",
          "default" => 1000,
          "minimum" => 1,
          "maximum" => 10000,
        ],
        "format" => [
          "type" => "string",
          "title" => "Text Format",
          "description" => "Text formatting option",
          "default" => "plain",
          "enum" => ["plain", "html", "markdown"],
        ],
      ],
    ];
  }

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

}
