<?php

declare(strict_types=1);

namespace Drupal\flowdrop_memory\Service;

use Drupal\Core\Cache\CacheBackendInterface;
use Drupal\Core\Extension\ModuleHandlerInterface;
use Drupal\Core\Plugin\DefaultPluginManager;
use Drupal\flowdrop_memory\Attribute\MemoryBackend;
use Drupal\flowdrop_memory\Plugin\MemoryBackend\MemoryBackendInterface;

/**
 * Plugin manager for FlowDrop memory backend plugins.
 *
 * Discovers backend plugins from the Plugin/MemoryBackend/ directory in any
 * installed module. Built-in backends: static, cached, entity.
 *
 * To register a custom backend, create a class that:
 * 1. Extends AbstractMemoryBackend (or implements MemoryBackendInterface)
 * 2. Uses the #[MemoryBackend] attribute
 * 3. Is placed in your module's Plugin/MemoryBackend/ directory
 *
 * Example:
 * @code
 * namespace Drupal\my_module\Plugin\MemoryBackend;
 *
 * #[MemoryBackend(id: "redis", label: new TranslatableMarkup("Redis"), persistent: TRUE, supports_ttl: TRUE)]
 * class RedisMemoryBackend extends AbstractMemoryBackend { ... }
 * @endcode
 *
 * @see \Drupal\flowdrop_memory\Attribute\MemoryBackend
 * @see \Drupal\flowdrop_memory\Plugin\MemoryBackend\MemoryBackendInterface
 *
 * @internal
 */
class MemoryBackendPluginManager extends DefaultPluginManager {

  /**
   * Constructs a new MemoryBackendPluginManager.
   *
   * @param \Traversable $namespaces
   *   An object that implements \Traversable which contains the root paths
   *   keyed by the corresponding namespace to look for plugin implementations.
   * @param \Drupal\Core\Cache\CacheBackendInterface $cache_backend
   *   The cache backend.
   * @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
   *   The module handler.
   */
  public function __construct(
    \Traversable $namespaces,
    CacheBackendInterface $cache_backend,
    ModuleHandlerInterface $module_handler,
  ) {
    parent::__construct(
      'Plugin/MemoryBackend',
      $namespaces,
      $module_handler,
      MemoryBackendInterface::class,
      MemoryBackend::class,
    );

    $this->setCacheBackend($cache_backend, 'flowdrop_memory_backend_plugins');
    $this->alterInfo('flowdrop_memory_backend_info');
  }

  /**
   * {@inheritdoc}
   *
   * @return \Drupal\flowdrop_memory\Plugin\MemoryBackend\MemoryBackendInterface
   *   The memory backend plugin instance.
   */
  public function createInstance($plugin_id, array $configuration = []): MemoryBackendInterface {
    $instance = $this->getFactory()->createInstance($plugin_id, $configuration);

    if (!$instance instanceof MemoryBackendInterface) {
      throw new \InvalidArgumentException(sprintf(
        "Memory backend plugin '%s' must implement MemoryBackendInterface.",
        $plugin_id,
      ));
    }

    return $instance;
  }

}
