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

/**
 * Event type for entity update events.
 *
 * Triggers when an existing entity is updated and saved.
 * This event fires after the entity has been successfully updated.
 * The original entity state (before the update) is available.
 */
#[FlowDropEventType(
  id: "entity.update",
  label: new TranslatableMarkup("Entity Update"),
  description: new TranslatableMarkup("Triggered when an existing entity is updated"),
  category: "entity",
  defaultOrchestrator: "asynchronous",
  defaultExecutionMode: "async",
  supportedEntityTypes: [],
)]
class EntityUpdate 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 update events.");
    }

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

    // Add update-specific data.
    $data["is_new"] = FALSE;
    $data["operation"] = "update";
    $data["has_original"] = $originalEntity !== NULL;

    return $data;
  }

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

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

}
