<?php

namespace Drupal\Tests\acquia_contenthub_subscriber\Kernel\EventSubscriber\HandleWebhook;

use Drupal\acquia_contenthub\AcquiaContentHubEvents;
use Drupal\acquia_contenthub_subscriber\ContentHubImportQueue;
use Drupal\acquia_contenthub_subscriber\SubscriberTracker;
use Drupal\Tests\acquia_contenthub\Kernel\EventSubscriber\HandleWebhook\PurgeTestBase;
use Drupal\Tests\acquia_contenthub_subscriber\Traits\SubscriberTrackerTestTrait;

/**
 * Tests purge operation on subscriber.
 *
 * PR: on purge operation the subscriber clears the queue and recreates the
 * client CDF.
 *
 * @coversDefaultClass \Drupal\acquia_contenthub_subscriber\EventSubscriber\HandleWebhook\Purge
 *
 * @group acquia_contenthub_subscriber
 *
 * @requires module depcalc
 */
class SubscriberPurgeTest extends PurgeTestBase {

  use SubscriberTrackerTestTrait;

  /**
   * {@inheritdoc}
   */
  protected static $modules = [
    'acquia_contenthub_subscriber',
  ];

  /**
   * {@inheritdoc}
   *
   * @throws \Exception
   */
  protected function setUp(): void {
    parent::setUp();

    $this->installSchema('acquia_contenthub_subscriber', [SubscriberTracker::IMPORT_TRACKING_TABLE]);
  }

  /**
   * Tests the truncation of tracking and queue tables.
   *
   * @throws \Exception
   */
  public function testOnPurgeQueueIsTruncatedTrackingTableIsNot(): void {
    $this->populateTrackingTableWithRandomData(50);
    $this->populateQueueTableWithRandomData(15, ContentHubImportQueue::QUEUE_NAME);

    $queued_items = $this->container->get('queue')
      ->get(ContentHubImportQueue::QUEUE_NAME)
      ->numberOfItems();

    $this->assertNumberOfRows(SubscriberTracker::IMPORT_TRACKING_TABLE, 50);
    $this->assertEquals(15, $queued_items);

    $event = $this->newHandleWebhookEvent([
      'status' => 'successful',
      'crud' => 'purge',
    ]);
    $this->container->get('event_dispatcher')->dispatch($event, AcquiaContentHubEvents::HANDLE_WEBHOOK);

    $queued_items = $this->container->get('queue')
      ->get(ContentHubImportQueue::QUEUE_NAME)
      ->numberOfItems();

    $this->assertNumberOfRows(SubscriberTracker::IMPORT_TRACKING_TABLE, 50);
    $this->assertEquals(0, $queued_items);
  }

  /**
   * {@inheritdoc}
   */
  protected function getQueueName(): string {
    return ContentHubImportQueue::QUEUE_NAME;
  }

  /**
   * {@inheritdoc}
   */
  protected function getTrackingTableName(): string {
    return SubscriberTracker::IMPORT_TRACKING_TABLE;
  }

}
