<?php

namespace Drupal\acquia_contenthub\Libs\Common;

use Acquia\ContentHubClient\ContentHubClient;
use Drupal\acquia_contenthub\Client\ClientFactory;
use Drupal\acquia_contenthub\Exception\ContentHubClientException;

/**
 * Ensures the retrieval of a Content Hub Client.
 */
trait EnsureContentHubClientTrait {

  /**
   * Content Hub Client factory.
   *
   * @var \Drupal\acquia_contenthub\Client\ClientFactory
   *
   * @throws \Drupal\acquia_contenthub\Exception\ContentHubClientException
   */
  protected ClientFactory $clientFactory;

  /**
   * Returns the client from Content Hub Client factory if available.
   *
   * @return \Acquia\ContentHubClient\ContentHubClient
   *   Ensures it returns a ContentHubClient.
   *
   * @throws \Drupal\acquia_contenthub\Exception\ContentHubClientException
   *   Thrown if ContentHubClient cannot be instantiated.
   */
  public function getClient(): ContentHubClient {
    $client = $this->clientFactory->getClient();
    if (!$client instanceof ContentHubClient) {
      $msg = 'Error trying to connect to the Content Hub. Make sure this site is registered to Content hub.';
      throw new ContentHubClientException($msg);
    }
    return $client;
  }

}
