<?php

declare(strict_types=1);

namespace Drupal\flowdrop_trigger\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;

/**
 * Trigger node processor backed by FlowDropTriggerConfig entity.
 *
 * This processor represents a trigger in the visual workflow editor.
 * When a trigger node is dropped in the editor, a FlowDropTriggerConfig
 * entity is created via the API. The node stores only a reference to the
 * entity via trigger_config_id.
 *
 * Actual trigger configuration (event type, conditions, orchestrator settings)
 * is loaded dynamically from the entity via the trigger config API.
 *
 * Entity ID format: {workflow_id}__{node_id}
 *
 * Implements ConfigEditProviderInterface to provide dynamic configuration
 * editing capabilities via REST API and admin forms.
 *
 * @see \Drupal\flowdrop_trigger\Entity\FlowDropTriggerConfig
 * @see \Drupal\flowdrop_trigger\Controller\TriggerConfigApiController
 * @see \Drupal\flowdrop\Plugin\FlowDropNodeProcessor\ConfigEditProviderInterface
 */
#[FlowDropNodeProcessor(
  id: "trigger",
  label: new TranslatableMarkup("Trigger"),
  description: "Trigger workflow on events (entity changes, user actions, cron, etc.)",
  version: "2.0.0"
)]
class Trigger extends AbstractTrigger implements ConfigEditProviderInterface {

  /**
   * {@inheritdoc}
   *
   * Minimal schema - trigger config is managed via the configure endpoint
   * which accepts workflow and node IDs. No need to store trigger_config_id
   * in the node as it's derived from workflow_id and node_id.
   */
  public function getParameterSchema(): array {
    $baseSchema = parent::getParameterSchema();

    // Terminal node variant - 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",
    ];
    return $baseSchema;
  }

  /**
   * {@inheritdoc}
   */
  public function getConfigEdit(): ConfigEdit {
    return new ConfigEdit(
      externalEditLink: new ExternalEditLink(
        url: "/admin/flowdrop/triggers/configure?workflow={workflowId}&node={nodeId}",
        label: "Configure Trigger",
        icon: "mdi:cog",
        description: "Open trigger configuration form in admin interface",
        // Map URL variables to node data.
        parameterMapping: [
          "workflowId" => "workflowId",
          "nodeId" => "id",
        ],
        openInNewTab: TRUE,
      ),
      preferDynamicSchema: FALSE,
      showRefreshButton: TRUE,
      loadingMessage: "Loading trigger configuration...",
      errorMessage: "Failed to load trigger configuration",
    );
  }

  /**
   * {@inheritdoc}
   *
   * Defines a generic output schema for trigger data passed to downstream
   * nodes.
   *
   * Since this is a generic trigger that can handle any event type, the output
   * schema is flexible. The actual data structure depends on the event type
   * configured in the trigger. Common properties are documented, but additional
   * properties may be present depending on the event source.
   */
  public function getOutputSchema(): array {
    return [
      "type" => "object",
      "title" => "Trigger Data",
      "description" => "Event data from the trigger. Structure varies by event type.",
      "properties" => [
        "data" => [
          "type" => "object",
          "title" => "Output",
          "description" => "Complete trigger output containing event-specific data. Properties vary based on event type.",
          "additionalProperties" => TRUE,
          "properties" => [
            "event_type" => [
              "type" => "string",
              "description" => "The event that triggered this workflow",
            ],
            "timestamp" => [
              "type" => "integer",
              "description" => "Unix timestamp when the event occurred",
            ],
            "trigger_config_id" => [
              "type" => "string",
              "description" => "The ID of the trigger configuration that fired",
            ],
            "trigger_node_id" => [
              "type" => "string",
              "description" => "The node ID of the trigger in the workflow",
            ],
          ],
        ],
      ],
    ];
  }

}
