<?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;
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.
 */
#[FlowDropEventType(
  id: "user.logout",
  label: new TranslatableMarkup("User Logout"),
  description: new TranslatableMarkup("Triggered when a user logs out"),
  category: "user",
  defaultOrchestrator: "asynchronous",
  defaultExecutionMode: "async",
  supportedEntityTypes: ["user"],
)]
class UserLogout extends FlowDropEventTypeBase implements FlowDropEventTypeInterface {

  /**
   * {@inheritdoc}
   */
  public function getCategory(): string {
    return "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" => [],
        ],
      ],
    ];
  }

}
