<?php

namespace Drupal\miniorange_2fa\Plugin;

use Drupal\Core\Plugin\DefaultPluginManager;
use Drupal\Core\Cache\CacheBackendInterface;
use Drupal\Core\Extension\ModuleHandlerInterface;
use Drupal\miniorange_2fa\Annotation\AuthenticationType;

/**
 * Manages discovery and instantiation of authentication type plugins.
 */
class AuthenticationTypeManager extends DefaultPluginManager {

  /**
   * Constructs a new AuthenticationTypeManager.
   *
   * @param \Traversable $namespaces
   *   An object that maps the root namespace to the path where to look for plugins.
   * @param \Drupal\Core\Cache\CacheBackendInterface $cache_backend
   *   Cache backend for plugin definitions.
   * @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
   *   Module handler.
   */
  public function __construct(\Traversable $namespaces, CacheBackendInterface $cache_backend, ModuleHandlerInterface $module_handler) {
    parent::__construct(
      'Plugin/AuthenticationType',
      $namespaces,
      $module_handler,
      AuthenticationTypeInterface::class,
      AuthenticationType::class
    );

    $this->alterInfo('miniorange_2fa_authentication_type_info');
    $this->setCacheBackend($cache_backend, 'miniorange_2fa_authentication_type_plugins');
  }

  /**
   * Gets an instance of a plugin by plugin ID.
   *
   * @param string $plugin_id
   *   The plugin ID.
   *
   * @return \Drupal\miniorange_2fa\Plugin\AuthenticationTypeInterface|null
   *   The plugin instance, or NULL if not found.
   */
  public function getPluginById(string $plugin_id): ?AuthenticationTypeInterface {
    if ($this->hasDefinition($plugin_id)) {
      return $this->createInstance($plugin_id);
    }
    return NULL;
  }

  /**
   * Gets all enabled plugin definitions sorted by weight.
   *
   * @return array
   *   Array of sorted plugin definitions.
   */
  public function getSortedDefinitions(): array {
    $definitions = $this->getDefinitions();

    uasort($definitions, function ($a, $b) {
      return ($a['weight'] ?? 0) <=> ($b['weight'] ?? 0);
    });

    return $definitions;
  }

  /**
   * Gets a plugin by its code (e.g., 'SMS', 'TOTP').
   *
   * @param string $code
   *   The unique code of the plugin.
   *
   * @return \Drupal\miniorange_2fa\Plugin\AuthenticationTypeInterface|null
   *   The matching plugin, or NULL if none found.
   */
  public function getPluginByCode(string $code): ?AuthenticationTypeInterface {
    foreach ($this->getDefinitions() as $id => $definition) {
      if (isset($definition['code']) && strtolower($definition['code']) === strtolower($code)) {
        return $this->createInstance($id);
      }
    }
    return NULL;
  }

}
