<?php

namespace Drupal\acquia_contenthub\Commands;

use Consolidation\AnnotatedCommand\CommandError;
use Drupal\acquia_contenthub\Client\ClientFactory;
use Drush\Commands\DrushCommands;

/**
 * Provides command to execute a re-index operation.
 */
class AcquiaContentHubReindexCommands extends DrushCommands {

  /**
   * Error codes for various events.
   */
  protected const ERR_CLIENT = 1;
  protected const ERR_REINDEX = 2;

  /**
   * The Content Hub Client factory service.
   *
   * @var \Drupal\acquia_contenthub\Client\ClientFactory
   */
  protected $factory;

  /**
   * The client used to communicate with Content Hub.
   *
   * @var \Acquia\ContentHubClient\ContentHubClient
   */
  protected $client;

  /**
   * Constructs this object.
   *
   * @param \Drupal\acquia_contenthub\Client\ClientFactory $factory
   *   The client factory service.
   */
  public function __construct(ClientFactory $factory) {
    parent::__construct();

    $this->factory = $factory;
  }

  /**
   * Check if Content Hub Client is available.
   *
   * @hook validate acquia:contenthub:reindex
   *
   * @throws \Exception
   */
  public function checkClient(): ?CommandError {
    $this->client = $this->factory->getClient();
    if ($this->client) {
      return NULL;
    }
    return new CommandError('Client is not available. Please check configuration or register the client!', self::ERR_CLIENT);
  }

  /**
   * Reindex entities exported to Content Hub.
   *
   * The command will initiate a re-index operation in Content Hub. This will
   * take some time depending on the amount of entities.
   *
   * @command acquia:contenthub:reindex
   *   Reindex entities stored in Content Hub.
   * @aliases ach-reindex
   */
  public function reindexEntities(): ?CommandError {
    $answer = $this->io()->confirm('Initiating reindex. This might take a while depending on the amount of entities in Content hub. Are you sure you want to continue?');
    if (!$answer) {
      $this->io()->warning('Terminating reindex operation. Exiting...');
      return NULL;
    }

    $this->io()->comment('The progress and different states can be tracked on Content Hub Dashboard > Logs page.');
    try {
      $resp = $this->client->reindex();
    }
    catch (\Exception $e) {
      return new CommandError(sprintf(
        'Cannot initiate reindex: %s', $e->getMessage()
      ), self::ERR_REINDEX);
    }

    if (isset($resp['success']) && $resp['success'] === TRUE) {
      $this->io()->success('Re-index has been received. Please check back later, this might take a while!');
      return NULL;
    }

    $this->io()->warning('Unexpected response from Content Hub. Please check Content Hub Dashboard!');
    return NULL;
  }

}
