<?php

declare(strict_types=1);

namespace Drupal\flowdrop_trigger\Plugin\FlowDropEventType;

use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\flowdrop_trigger\Attribute\FlowDropEventType;
use Drupal\flowdrop_trigger\Enum\EventCategory;
use Drupal\flowdrop_trigger\Enum\TriggerExecutionMode;
use Drupal\flowdrop_trigger\FlowDropEventTypeInterface;
use Drupal\flowdrop_trigger\Plugin\FlowDropEventTypeBase;

/**
 * Event type for form validation events.
 *
 * Triggers when a form is being validated.
 * This event fires during form validation, before submission.
 *
 * @internal This class is not part of the public API and may change without notice.
 */
#[FlowDropEventType(
  id: "form.validate",
  label: new TranslatableMarkup("Form Validate"),
  description: new TranslatableMarkup("Triggered when a form is being validated"),
  category: EventCategory::Form,
  defaultOrchestrator: "flowdrop_runtime:synchronous",
  defaultExecutionMode: TriggerExecutionMode::Sync,
  supportedEntityTypes: [],
)]
class FormValidate extends FlowDropEventTypeBase implements FlowDropEventTypeInterface {

  /**
   * {@inheritdoc}
   */
  public function getCategory(): EventCategory {
    return EventCategory::Form;
  }

  /**
   * {@inheritdoc}
   */
  public function extractTriggerData(
    ?EntityInterface $entity,
    ?EntityInterface $originalEntity = NULL,
    array $context = [],
  ): array {
    // For form events, we don't have an entity, so we extract from context.
    $formId = $context["form_id"] ?? "";
    $formValues = $context["form_values"] ?? [];
    $form = $context["form"] ?? [];
    $formState = $context["form_state"] ?? [];
    $user = $context["user"] ?? NULL;

    $data = [
      "event_type" => $this->getEventId(),
      "form_id" => $formId,
      "form" => $form,
      "form_values" => $formValues,
      "form_state" => $formState,
      "timestamp" => time(),
    ];

    // Add entity information if form is entity-based.
    if (isset($context["entity"])) {
      $entity = $context["entity"];
      if (is_object($entity) && method_exists($entity, "getEntityTypeId")) {
        $data["entity_type"] = $entity->getEntityTypeId();
        $data["entity_id"] = $entity->id();
        $data["bundle"] = method_exists($entity, "bundle") ? $entity->bundle() : NULL;
        $data["entity"] = $entity;
      }
    }

    // Add user information.
    if ($user !== NULL) {
      if (is_object($user) && method_exists($user, "id")) {
        $data["user"] = [
          "uid" => $user->id(),
          "username" => method_exists($user, "getAccountName") ? $user->getAccountName() : NULL,
          "email" => method_exists($user, "getEmail") ? $user->getEmail() : NULL,
        ];
      }
      elseif (is_array($user)) {
        $data["user"] = $user;
      }
    }

    // Add operation.
    $data["operation"] = "validate";

    return $data;
  }

  /**
   * {@inheritdoc}
   */
  public function getParameterSchema(): array {
    return [
      "type" => "object",
      "properties" => [
        "form_ids" => [
          "type" => "array",
          "title" => "Form IDs",
          "description" => "Only trigger for these form IDs (empty = all)",
          "items" => ["type" => "string"],
          "default" => [],
        ],
      ],
    ];
  }

}
