<?php

declare(strict_types=1);

namespace Drupal\flowdrop_orchestration_connector\Plugin\FlowDropEventType;

use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\flowdrop_orchestration\Service\Orchestrator\OrchestratorHelperInterface;
use Drupal\flowdrop_trigger\Attribute\FlowDropEventType;
use Drupal\flowdrop_trigger\Enum\EventCategory;
use Drupal\flowdrop_trigger\FlowDropEventTypeInterface;
use Drupal\flowdrop_trigger\Plugin\FlowDropEventTypeBase;

/**
 * Event type for external orchestration platform invocations.
 *
 * This trigger fires when an external automation platform (like Activepieces)
 * invokes a FlowDrop workflow via the Orchestration module API.
 *
 * Unlike entity or user events, this trigger doesn't rely on Drupal hooks.
 * Instead, it's explicitly invoked when the Orchestration module's
 * execute endpoint is called with a FlowDrop workflow service.
 *
 * The trigger receives arbitrary data from the external platform as input,
 * making it ideal for building workflows that respond to external events
 * (webhooks from third-party services, scheduled automation tasks, etc.).
 *
 * @see \Drupal\flowdrop_orchestration_connector\Service\InvokeTriggerService
 * @see \Drupal\flowdrop_orchestration_connector\ServicesProvider
 *
 * @internal This class is not part of the public API and may change without notice.
 */
#[FlowDropEventType(
  id: "orchestration.invoke",
  label: new TranslatableMarkup("Orchestration Invoke"),
  description: new TranslatableMarkup("Triggered when an external platform invokes this workflow via the Orchestration API"),
  category: EventCategory::Integration,
  defaultOrchestrator: OrchestratorHelperInterface::SYNCHRONOUS_PIPELINE,
  defaultExecutionMode: "sync",
  supportedEntityTypes: [],
)]
class OrchestrationInvoke extends FlowDropEventTypeBase implements FlowDropEventTypeInterface {

  /**
   * {@inheritdoc}
   *
   * For orchestration invocations, entity is not used. Instead, the context
   * array contains the invocation payload from the external platform.
   */
  public function extractTriggerData(
    ?EntityInterface $entity,
    ?EntityInterface $originalEntity = NULL,
    array $context = [],
  ): array {
    // Extract data from the orchestration invocation context.
    return [
      "event_type" => $this->getEventId(),
      "timestamp" => time(),
      "source" => "orchestration",
      "invocation_id" => $context["invocation_id"] ?? uniqid("invoke_", TRUE),
      "service_id" => $context["service_id"] ?? "",
      "workflow_id" => $context["workflow_id"] ?? "",
      "trigger_config_id" => $context["trigger_config_id"] ?? "",
      "trigger_node_id" => $context["trigger_node_id"] ?? "",
      // The payload from the external platform is passed through as-is.
      // This allows workflows to access any data sent by the automation tool.
      "payload" => $context["payload"] ?? [],
      // Include any additional context fields.
      "metadata" => $context["metadata"] ?? [],
    ];
  }

  /**
   * {@inheritdoc}
   *
   * Orchestration triggers don't need entity-based conditions since they're
   * invoked explicitly by ID. The parameter schema defines what data the
   * external platform can provide.
   */
  public function getParameterSchema(): array {
    return [
      "type" => "object",
      "title" => "Orchestration Invoke Configuration",
      "description" => "Configuration for external platform invocation triggers.",
      "properties" => [
        "description" => [
          "type" => "string",
          "title" => "Description",
          "description" => "A description of what this trigger does (shown to external platform users).",
          "default" => "",
        ],
        "payload_schema" => [
          "type" => "object",
          "title" => "Payload Schema",
          "description" => "JSON Schema defining the expected payload structure from external platforms.",
          "additionalProperties" => TRUE,
          "default" => [
            "type" => "object",
            "additionalProperties" => TRUE,
          ],
        ],
        "required_fields" => [
          "type" => "array",
          "title" => "Required Fields",
          "description" => "Fields that must be provided by the external platform.",
          "items" => [
            "type" => "string",
          ],
          "default" => [],
        ],
        "response_mode" => [
          "type" => "string",
          "title" => "Response Mode",
          "description" => "How to respond to the external platform after execution.",
          "enum" => ["immediate", "callback"],
          "default" => "immediate",
        ],
      ],
    ];
  }

}
