<?php

namespace Drupal\Tests\acquia_contenthub\Traits;

use Drupal\acquia_contenthub_subscriber\ContentHubImportQueue;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Tests\RandomGeneratorTrait;

/**
 * Provides helper functions for tests using queues.
 */
trait QueueTestTrait {

  use CommonRandomGenerator;
  use RandomGeneratorTrait;

  /**
   * Populates queue tables with random data.
   *
   * The queue tables can be either from the publisher or the subscriber.
   *
   * @param int|null $num_of_rows
   *   The number of rows to insert.
   * @param string $queue_name
   *   The queue name.
   *
   * @throws \Exception
   */
  public function populateQueueTableWithRandomData(?int $num_of_rows, string $queue_name): void {
    $amount = $num_of_rows ?: random_int(100, 500);
    $queue = \Drupal::queue($queue_name);
    for ($i = 0; $i < $amount; $i++) {
      $data = new \stdClass();
      $data->uuid = $this->generateUuid();
      $data->type = $this->randomMachineName(random_int(5, 20));
      $queue->createItem($data);
    }
  }

  /**
   * Adds entities to the provided queue.
   *
   * Creates queue items with type and uuid attributes.
   *
   * @param string $queue_name
   *   The name of the queue.
   * @param \Drupal\Core\Entity\EntityInterface ...$entities
   *   The entities to add.
   *
   * @throws \Exception
   */
  protected function addEntitiesToQueue(string $queue_name, EntityInterface ...$entities): void {
    $queue = \Drupal::queue($queue_name);
    $queue->deleteQueue();
    foreach ($entities as $entity) {
      $obj = new \stdClass();
      $obj->type = $entity->getEntityTypeId();
      $obj->uuid = $entity->uuid();
      $queue->createItem($obj);
    }
  }

  /**
   * Ensures the queue table exists.
   *
   * The table creation is encapsulated into DatabaseQueue->createItem()
   * function. Therefore, we create an item then delete the item to ensure that
   * the table gets created.
   *
   * @throws \Exception
   */
  public function ensureQueueTableExists(): void {
    /** @var \Drupal\Core\Queue\QueueInterface $queue */
    $queue = $this->container->get('queue')->get(ContentHubImportQueue::QUEUE_NAME);
    $data = new \stdClass();
    $data->uuids = '1,2';
    $queue->createItem($data);
    $queue->deleteQueue();
  }

}
