<?php

namespace Drupal\acquia_contenthub_publisher\Commands;

use Drupal\acquia_contenthub\Client\ClientFactory;
use Drupal\acquia_contenthub\ContentHubConnectionManager;
use Drupal\acquia_contenthub\Settings\ContentHubConfigurationInterface;
use Drupal\Core\Database\Connection;
use Drupal\Core\Extension\ModuleHandlerInterface;
use Drupal\Core\Logger\LoggerChannelFactoryInterface;
use Drupal\Core\State\StateInterface;
use Drupal\Core\Url;
use Drush\Commands\DrushCommands;

/**
 * Drush commands for Acquia Content Hub Publishers.
 *
 * @package Drupal\acquia_contenthub_publisher\Commands
 */
class AcquiaContentHubPublisherCommands extends DrushCommands {

  /**
   * The database connection.
   *
   * @var \Drupal\Core\Database\Connection
   */
  protected $database;

  /**
   * Content Hub Client Factory.
   *
   * @var \Drupal\acquia_contenthub\Client\ClientFactory
   */
  protected $clientFactory;

  /**
   * Logger Service.
   *
   * @var \Psr\Log\LoggerInterface
   */
  protected $chLogger;

  /**
   * State Service.
   *
   * @var \Drupal\Core\State\StateInterface
   */
  protected $state;

  /**
   * Module Handler Service.
   *
   * @var \Drupal\Core\Extension\ModuleHandlerInterface
   */
  protected $moduleHandler;

  /**
   * The Content Hub Connection Manager.
   *
   * @var \Drupal\acquia_contenthub\ContentHubConnectionManager
   */
  protected $connectionManager;

  /**
   * CH configurations.
   *
   * @var \Drupal\acquia_contenthub\Settings\ContentHubConfigurationInterface
   */
  protected ContentHubConfigurationInterface $achConfigurations;

  /**
   * Public Constructor.
   *
   * @param \Drupal\acquia_contenthub\Settings\ContentHubConfigurationInterface $ach_configurations
   *   The configuration factory.
   * @param \Drupal\Core\Database\Connection $database
   *   Database connection.
   * @param \Drupal\acquia_contenthub\Client\ClientFactory $client_factory
   *   Client Factory.
   * @param \Drupal\Core\Logger\LoggerChannelFactoryInterface $logger_factory
   *   Logger factory service.
   * @param \Drupal\Core\State\StateInterface $state
   *   State Service.
   * @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
   *   Module Handler Service.
   * @param \Drupal\acquia_contenthub\ContentHubConnectionManager $connection_manager
   *   The Content Hub Connection Manager.
   */
  public function __construct(ContentHubConfigurationInterface $ach_configurations, Connection $database, ClientFactory $client_factory, LoggerChannelFactoryInterface $logger_factory, StateInterface $state, ModuleHandlerInterface $module_handler, ContentHubConnectionManager $connection_manager) {
    $this->achConfigurations = $ach_configurations;
    $this->database = $database;
    $this->clientFactory = $client_factory;
    $this->chLogger = $logger_factory->get('acquia_contenthub_publisher');
    $this->state = $state;
    $this->moduleHandler = $module_handler;
    $this->connectionManager = $connection_manager;
  }

  /**
   * Publisher Upgrade Command.
   *
   * @command acquia:contenthub-publisher-upgrade
   * @aliases ach-publisher-upgrade,ach-puup
   */
  public function upgrade() {
    // Only proceed if there still exists a legacy tracking table.
    if (!$this->database->schema()->tableExists('acquia_contenthub_entities_tracking')) {
      $this->chLogger->warning(dt('Legacy tracking table does not exist.'));
      return;
    }

    // Make sure webhook stored is actually registered for this site in Plexus.
    $settings = $this->achConfigurations->getSettings();
    $client = $this->clientFactory->getClient($settings);
    if (!$client->getSettings()->getWebhook()) {
      // Proceed to register a webhook in HMAC v2.
      $webhook_url = Url::fromUri('internal:' . '/acquia-contenthub/webhook', [
        'absolute' => TRUE,
      ])->toString();
      $webhook = $client->getWebHook($webhook_url);
      if (empty($webhook)) {
        $response = $this->connectionManager->registerWebhook($webhook_url);
        if (isset($response['success']) && FALSE === $response['success']) {
          $message = dt('Registering webhooks encountered an error (code @code). @reason', [
            '@code' => $response['error']['code'],
            '@reason' => $response['error']['message'],
          ]);
          $this->chLogger->error($message);
          return;
        }
      }
    }
    // Enqueue all exported entities.
    $path = $this->moduleHandler->getModule('acquia_contenthub_publisher')->getPath();
    $batch = [
      'title' => dt('Exporting'),
      'operations' => [
        ['acquia_contenthub_publisher_enqueue_exported_entities', []],
      ],
      'finished' => 'acquia_contenthub_publisher_enqueue_exported_entities_finished',
      'file' => $path . '/acquia_contenthub_publisher.migrate.inc',
    ];
    batch_set($batch);
    drush_backend_batch_process();
  }

}
