<?php

declare(strict_types=1);

namespace Drupal\flowdrop_orchestration_connector\Plugin\FlowDropNodeProcessor;

use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\flowdrop\Attribute\FlowDropNodeProcessor;
use Drupal\flowdrop\DTO\ConfigEdit\ConfigEdit;
use Drupal\flowdrop\DTO\ConfigEdit\ExternalEditLink;
use Drupal\flowdrop\Plugin\FlowDropNodeProcessor\ConfigEditProviderInterface;
use Drupal\flowdrop_trigger\Plugin\FlowDropNodeProcessor\AbstractTrigger;

/**
 * Orchestration Trigger node processor for external platform invocations.
 *
 * This trigger node allows workflows to be invoked by external automation
 * platforms (like Activepieces) via the Orchestration module API. When an
 * external platform calls the FlowDrop service through Orchestration's
 * /orchestration/service/execute endpoint, this trigger fires with the
 * provided payload data.
 *
 * Use cases:
 * - Respond to webhooks from third-party services (Stripe, GitHub, etc.)
 * - Execute workflows on a schedule from external automation platforms
 * - Chain FlowDrop workflows with external automation sequences
 * - Process data pushed from CRMs, email platforms, or other tools
 *
 * The trigger's entity ID follows format: {workflow_id}__{node_id} and is
 * stored in FlowDropTriggerConfig with event_type = "orchestration.invoke".
 *
 * @see \Drupal\flowdrop_orchestration_connector\Plugin\FlowDropEventType\OrchestrationInvoke
 * @see \Drupal\flowdrop_orchestration_connector\ServicesProvider
 *
 * @internal This class is not part of the public API and may change without notice.
 */
#[FlowDropNodeProcessor(
  id: "orchestration_trigger",
  label: new TranslatableMarkup("Orchestration Trigger"),
  description: "Trigger workflow from external automation platforms (Activepieces, etc.)",
  version: "1.0.0"
)]
class OrchestrationTrigger extends AbstractTrigger implements ConfigEditProviderInterface {

  /**
   * {@inheritdoc}
   *
   * Schema for orchestration trigger configuration.
   * Most configuration is managed via the FlowDropTriggerConfig entity.
   */
  public function getParameterSchema(): array {
    $baseSchema = parent::getParameterSchema();

    // Terminal node variant - orchestration triggers are always "start" nodes.
    $baseSchema["properties"]["variant"] = [
      "type" => "string",
      "title" => "Variant",
      "description" => "Terminal node variant (start for triggers)",
      "enum" => ["start"],
      "default" => "start",
      "format" => "hidden",
    ];

    // Event type is fixed for this trigger.
    $baseSchema["properties"]["event_type"] = [
      "type" => "string",
      "title" => "Event Type",
      "description" => "The event type for this trigger",
      "default" => "orchestration.invoke",
      "format" => "hidden",
    ];

    return $baseSchema;
  }

  /**
   * {@inheritdoc}
   */
  public function getConfigEdit(): ConfigEdit {
    return new ConfigEdit(
      externalEditLink: new ExternalEditLink(
        url: "/admin/flowdrop/triggers/configure?workflow={workflowId}&node={nodeId}",
        label: "Configure Orchestration Trigger",
        icon: "mdi:webhook",
        description: "Configure how external platforms can invoke this workflow",
        parameterMapping: [
          "workflowId" => "workflowId",
          "nodeId" => "id",
        ],
        openInNewTab: TRUE,
      ),
      preferDynamicSchema: FALSE,
      showRefreshButton: TRUE,
      loadingMessage: "Loading trigger configuration...",
      errorMessage: "Failed to load trigger configuration",
    );
  }

  /**
   * {@inheritdoc}
   *
   * Defines the output schema for orchestration trigger data.
   * The payload structure depends on what the external platform sends.
   */
  public function getOutputSchema(): array {
    return [
      "type" => "object",
      "title" => "Orchestration Trigger Output",
      "description" => "Data received from external automation platform invocation.",
      "properties" => [
        "data" => [
          "type" => "object",
          "title" => "Trigger Data",
          "description" => "Complete trigger output containing invocation data from external platform.",
          "additionalProperties" => TRUE,
          "properties" => [
            "event_type" => [
              "type" => "string",
              "description" => "The event type (orchestration.invoke)",
            ],
            "timestamp" => [
              "type" => "integer",
              "description" => "Unix timestamp when the invocation occurred",
            ],
            "invocation_id" => [
              "type" => "string",
              "description" => "Unique identifier for this invocation",
            ],
            "source" => [
              "type" => "string",
              "description" => "Source of the invocation (orchestration)",
            ],
            "service_id" => [
              "type" => "string",
              "description" => "The orchestration service ID that was called",
            ],
            "workflow_id" => [
              "type" => "string",
              "description" => "The workflow ID being executed",
            ],
            "trigger_config_id" => [
              "type" => "string",
              "description" => "The trigger configuration ID",
            ],
            "trigger_node_id" => [
              "type" => "string",
              "description" => "The node ID of this trigger in the workflow",
            ],
            "payload" => [
              "type" => "object",
              "description" => "The payload data sent by the external platform",
              "additionalProperties" => TRUE,
            ],
            "metadata" => [
              "type" => "object",
              "description" => "Additional metadata about the invocation",
              "additionalProperties" => TRUE,
            ],
          ],
        ],
      ],
    ];
  }

}
