<?php

namespace Drupal\acquia_contenthub\Libs\ServiceQueue;

use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;

/**
 * Registers queue item action handlers.
 *
 * Any service tagged with 'queue_item_action' will be automatically registered
 * as an action handler for queue items. The actions are processed in the order
 * they are discovered, with the first matching action being used.
 *
 * Example:
 * @code
 * # In your_module.services.yml
 * your_module.queue_item_action.custom_action:
 *   class: Drupal\your_module\MyCustomAction
 *   arguments: ['@event_dispatcher', '@your_custom_service']
 *   tags:
 *     - { name: queue_item_action }
 * @endcode
 *
 * The custom action class must implement QueueItemActionInterface:
 * @code
 * class MyCustomAction implements QueueItemActionInterface {
 *   public function canHandle(QueueItem $queue_item): bool {
 *     return $queue_item->isAction('my_custom_action');
 *   }
 *
 *   public function execute(array $queue_items, ContentHubClient $client): void {
 *     // Custom processing logic
 *   }
 * }
 * @endcode
 */
class QueueItemActionCompilerPass implements CompilerPassInterface {

  public const SERVICE_TAG = 'queue_item_action';

  /**
   * {@inheritdoc}
   */
  public function process(ContainerBuilder $container): void {
    if (!$container->hasDefinition('acquia_contenthub.service_queue_handler')) {
      return;
    }

    $definition = $container->findDefinition('acquia_contenthub.service_queue_handler');
    $tagged_services = $container->findTaggedServiceIds(static::SERVICE_TAG);

    foreach ($tagged_services as $service => $tags) {
      $definition->addMethodCall('addAction', [new Reference($service)]);
    }
  }

}
