<?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;
use Drupal\user\UserInterface;

/**
 * Event type for user logout events.
 *
 * Triggers when a user logs out of the site.
 * This event fires after the session is destroyed.
 *
 * @internal This class is not part of the public API and may change without notice.
 */
#[FlowDropEventType(
  id: "user.logout",
  label: new TranslatableMarkup("User Logout"),
  description: new TranslatableMarkup("Triggered when a user logs out"),
  category: EventCategory::User,
  defaultOrchestrator: "flowdrop_runtime:asynchronous",
  defaultExecutionMode: TriggerExecutionMode::Async,
  supportedEntityTypes: ["user"],
)]
class UserLogout extends FlowDropEventTypeBase implements FlowDropEventTypeInterface {

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

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

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

    // Add user-specific data.
    $data["operation"] = "logout";

    if ($entity instanceof UserInterface) {
      $data["username"] = $entity->getAccountName();
      $data["email"] = $entity->getEmail();
      $data["roles"] = $entity->getRoles();
    }

    return $data;
  }

  /**
   * {@inheritdoc}
   */
  public function getParameterSchema(): array {
    return [
      "type" => "object",
      "properties" => [
        "roles" => [
          "type" => "array",
          "title" => "User Roles",
          "description" => "Only trigger for users with these roles (empty = all)",
          "items" => ["type" => "string"],
          "default" => [],
        ],
      ],
    ];
  }

}
