<?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 login events.
 *
 * Triggers when a user successfully logs into the site.
 * This event fires after authentication is complete.
 */
#[FlowDropEventType(
  id: "user.login",
  label: new TranslatableMarkup("User Login"),
  description: new TranslatableMarkup("Triggered when a user logs in"),
  category: "user",
  defaultOrchestrator: "asynchronous",
  defaultExecutionMode: "async",
  supportedEntityTypes: ["user"],
)]
class UserLogin 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 login events.");
    }

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

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

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

    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" => [],
        ],
      ],
    ];
  }

}
