<?php

namespace Drupal\acquia_contenthub\Commands;

use Drupal\acquia_contenthub\Client\ClientMetaDataManagerInterface;
use Drupal\acquia_contenthub\Commands\Traits\ColorizedOutputTrait;
use Drupal\acquia_contenthub\Exception\ContentHubClientException;
use Drush\Commands\DrushCommands;
use Psr\Log\LoggerInterface;

/**
 * Drush commands for sending client metadata.
 */
class AcquiaContentHubClientMetaDataCommands extends DrushCommands {

  use ColorizedOutputTrait;

  /**
   * Client Metadata Manager.
   *
   * @var \Drupal\acquia_contenthub\Client\ClientMetaDataManagerInterface
   */
  protected ClientMetaDataManagerInterface $metaDataManager;

  /**
   * Content hub logger.
   *
   * @var \Psr\Log\LoggerInterface
   */
  protected LoggerInterface $chLogger;

  /**
   * AcquiaContentHubClientMetaDataCommands constructor.
   *
   * @param \Drupal\acquia_contenthub\Client\ClientMetaDataManagerInterface $metadata_manager
   *   Client metadata manager.
   * @param \Psr\Log\LoggerInterface $ch_logger
   *   Content Hub logger.
   */
  public function __construct(ClientMetaDataManagerInterface $metadata_manager, LoggerInterface $ch_logger) {
    $this->metaDataManager = $metadata_manager;
    $this->chLogger = $ch_logger;
  }

  /**
   * Updates client metadata in CH service.
   *
   * @command acquia:contenthub-update-client-metadata
   * @aliases ach-ucm
   *
   * @throws \Exception
   */
  public function updateClientMetaData(): void {
    try {
      $result = $this->metaDataManager->updateClientMetadata();
      if ($result) {
        $this->output()
          ->writeln($this->info('Client metadata has been updated in service.'));
      }
      else {
        $this->output()
          ->writeln($this->info('Client metadata is already up-to-date.'));
      }
    }
    catch (ContentHubClientException $e) {
      $this->chLogger->error($e->getMessage());
      $this->output()
        ->writeln($this->error($e->getMessage()));
    }
    catch (\Exception $exception) {
      $msg = sprintf('Something went wrong while sending metadata to service: %s', $exception->getMessage());
      $this->chLogger->error($msg);
      $this->output()
        ->writeln($this->error($msg));
    }
  }

}
