<?php

declare(strict_types=1);

namespace Drupal\flowdrop_trigger\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\Enum\TriggerExecutionMode;
use Drupal\flowdrop_trigger\FlowDropEventTypeInterface;
use Drupal\flowdrop_trigger\Plugin\FlowDropEventTypeBase;

/**
 * Event type for entity insert events.
 *
 * Triggers when a new entity is created and saved to the database.
 * This event fires after the entity has been successfully inserted.
 *
 * @internal This class is not part of the public API and may change without notice.
 */
#[FlowDropEventType(
  id: "entity.insert",
  label: new TranslatableMarkup("Entity Insert"),
  description: new TranslatableMarkup("Triggered when a new entity is created"),
  category: EventCategory::Entity,
  defaultOrchestrator: OrchestratorHelperInterface::ASYNCHRONOUS,
  defaultExecutionMode: TriggerExecutionMode::Async,
  supportedEntityTypes: [],
)]
class EntityInsert extends FlowDropEventTypeBase implements FlowDropEventTypeInterface {

  /**
   * {@inheritdoc}
   */
  public function extractTriggerData(
    ?EntityInterface $entity,
    ?EntityInterface $originalEntity = NULL,
    array $context = [],
  ): array {
    if ($entity === NULL) {
      throw new \InvalidArgumentException("Entity cannot be NULL for entity insert events.");
    }

    $data = $this->getBaseTriggerData($entity);

    // Add insert-specific data.
    $data["is_new"] = TRUE;
    $data["operation"] = "insert";

    return $data;
  }

  /**
   * {@inheritdoc}
   */
  public function getParameterSchema(): array {
    $baseSchema = parent::getParameterSchema();

    // Entity insert doesn't need additional configuration beyond base.
    return $baseSchema;
  }

}
