<?php

namespace Drupal\Tests\acquia_contenthub_subscriber\Traits;

use Drupal\acquia_contenthub_subscriber\SubscriberTracker;
use Drupal\Tests\acquia_contenthub\Traits\CommonRandomGenerator;
use Drupal\Tests\RandomGeneratorTrait;

/**
 * Helper functions for subscriber tracker related tests.
 */
trait SubscriberTrackerTestTrait {

  use CommonRandomGenerator;
  use RandomGeneratorTrait;

  /**
   * Populates tracking table with random data.
   *
   * @param int|null $num_of_rows
   *   The number of rows to insert.
   *
   * @throws \Exception
   */
  public function populateTrackingTableWithRandomData(?int $num_of_rows): void {
    $amount = $num_of_rows ?: random_int(100, 500);
    $query = \Drupal::database()
      ->insert(SubscriberTracker::IMPORT_TRACKING_TABLE)
      ->fields([
        'entity_uuid', 'entity_type', 'entity_id', 'status',
        'first_imported', 'last_imported', 'hash', 'queue_id',
      ]);

    for ($i = 0; $i < $amount; $i++) {
      $query->values([
        'entity_type' => $this->randomMachineName(random_int(1, 20)),
        'entity_id' => $this->takeRandom([
          random_int(1, 100), $this->randomMachineName(random_int(1, 20)),
        ]),
        'entity_uuid' => $this->generateUuid(),
        'status' => $this->takeRandom(['imported', 'queued']),
        'first_imported' => time(),
        'last_imported' => time(),
        'hash' => sha1($this->randomString()),
        'queue_id' => $this->takeRandom(['', random_int(1, 10000)]),
      ]);
    }

    $query->execute();
  }

}
