<?php

namespace Drupal\acquia_contenthub_subscriber\Commands;

use Drupal\acquia_contenthub\Client\ClientFactory;
use Drupal\acquia_contenthub\Commands\Traits\ColorizedOutputTrait;
use Drupal\acquia_contenthub\Settings\ContentHubConfigurationInterface;
use Drupal\acquia_contenthub_subscriber\ContentHubImportQueue;
use Drupal\acquia_contenthub_subscriber\SubscriberTracker;
use Drush\Commands\DrushCommands;
use Symfony\Component\HttpFoundation\Response;

/**
 * Drush command for Acquia ContentHub Subscriber Interest List Purge.
 */
class AcquiaContentHubSubscriberInterestListCommands extends DrushCommands {

  use ColorizedOutputTrait;

  /**
   * Content Hub Client.
   *
   * @var \Acquia\ContentHubClient\ContentHubClient|bool
   */
  protected $client;

  /**
   * CH settings.
   *
   * @var \Acquia\ContentHubClient\Settings
   */
  protected $settings;

  /**
   * The Import Queue Service.
   *
   * @var \Drupal\acquia_contenthub_subscriber\ContentHubImportQueue
   */
  protected $importQueue;

  /**
   * The Subscriber Tracker Service.
   *
   * @var \Drupal\acquia_contenthub_subscriber\SubscriberTracker
   */
  protected $tracker;

  /**
   * AcquiaContentHubSubscriberInterestListCommands constructor.
   *
   * @param \Drupal\acquia_contenthub\Client\ClientFactory $factory
   *   Client Factory.
   * @param \Drupal\acquia_contenthub\Settings\ContentHubConfigurationInterface $ach_configuration
   *   CH Admin configurations.
   * @param \Drupal\acquia_contenthub_subscriber\ContentHubImportQueue $import_queue
   *   Import queue service.
   * @param \Drupal\acquia_contenthub_subscriber\SubscriberTracker $tracker
   *   Acquia Content Hub Subscriber Tracker.
   */
  public function __construct(ClientFactory $factory, ContentHubConfigurationInterface $ach_configuration, ContentHubImportQueue $import_queue, SubscriberTracker $tracker) {
    $this->client = $factory->getClient();
    $this->settings = $ach_configuration->getSettings();
    $this->importQueue = $import_queue;
    $this->tracker = $tracker;
  }

  /**
   * Perform a webhook interest list purge operation for current site.
   *
   * Deletes everything from import tracking table.
   * Deletes all the items in import queue.
   *
   * @command acquia:contenthub-webhook-interests-purge
   * @aliases ach-wi-purge
   *
   * @usage drush acquia:contenthub-webhook-interests-purge
   *   Purges interest list of current site's webhook.
   *
   * @throws \Exception
   */
  public function purgeInterestList(): int {
    $webhook_uuid = $this->settings->getWebhook('uuid');
    if (!$webhook_uuid) {
      $this->output()->writeln($this->error(dt('Webhook does not exist. Exiting...')));
      return 2;
    }
    $interest_list = $this->client->getInterestList($webhook_uuid, 'subscriber');
    $interest_list = array_keys($interest_list);
    if (empty($interest_list)) {
      $this->output()->writeln($this->info(dt('Interest list is empty. Nothing to purge.')));
      return 0;
    }
    $this->output()->writeln($this->info(dt('Purging interest list for webhook @webhook_uuid.', [
      '@webhook_uuid' => $webhook_uuid,
    ])));

    $chunks = array_chunk($interest_list, 1000);
    foreach ($chunks as $chunk) {
      $response = $this->client->deleteMultipleInterest($webhook_uuid, $chunk, 'subscriber');
      if ($response->getStatusCode() !== Response::HTTP_OK) {
        $this->output()->writeln($this->error(dt('Could not purge interest list: @e_message', [
          '@e_message' => (string) $response->getBody(),
        ])));
        return 3;
      }
    }
    $this->purgeImportQueue();
    $this->output()->writeln($this->info(dt('Interest list for webhook @webhook_uuid has been purged.', [
      '@webhook_uuid' => $webhook_uuid,
    ])));

    return 0;
  }

  /**
   * Purges import queue and deletes all the rows from import tracking table.
   */
  protected function purgeImportQueue(): void {
    $this->importQueue->purgeQueues();
    $this->output()->writeln($this->info(dt('All the items in the import queue have been purged.')));
    $this->tracker->deleteAll();
    $this->output()->writeln($this->info(dt('Tracking table has been reset.')));
  }

}
