<?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 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.
 *
 * @internal This class is not part of the public API and may change without notice.
 */
#[FlowDropEventType(
  id: "entity.update",
  label: new TranslatableMarkup("Entity Update"),
  description: new TranslatableMarkup("Triggered when an existing entity is updated"),
  category: EventCategory::Entity,
  defaultOrchestrator: "flowdrop_runtime:asynchronous",
  defaultExecutionMode: TriggerExecutionMode::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;
  }

}
