<?php

namespace Drupal\user_provisioning\Api;

use Drupal\user_provisioning\moUserProvisioningConstants;

/**
 * Provides helper methods for module authentication API calls.
 */
class MoAuthApi {
  /**
   * API key used for authenticated requests.
   *
   * @var string
   */
  private string $apiKey;
  /**
   * Customer identifier used for authenticated requests.
   *
   * @var string
   */
  private string $customerId;
  /**
   * HTTP client used for outbound API calls.
   *
   * @var mixed
   */
  private $httpClient;

  /**
   * Constructs the auth API helper.
   *
   * @param string $customerId
   *   The customer identifier.
   * @param string $apiKey
   *   The customer API key.
   */
  public function __construct($customerId = moUserProvisioningConstants::DEFAULT_CUSTOMER_ID, $apiKey = moUserProvisioningConstants::DEFAULT_API_KEY) {
    $this->customerId = $customerId;
    $this->apiKey = $apiKey;
    $this->httpClient = \Drupal::httpClient();
  }

  /**
   * This function is used to get the timestamp value.
   *
   * @return string
   *   The timestamp in milliseconds.
   */
  public function getTimeStamp() {
    $url = moUserProvisioningConstants::GET_TIMESTAMP;
    $fields = [];
    $currentTimeInMillis = $this->makeHttpClientCall($url, $fields);
    if (empty($currentTimeInMillis)) {
      $currentTimeInMillis = round(microtime(TRUE) * 1000);
      $currentTimeInMillis = number_format($currentTimeInMillis, 0, '', '');
    }
    return $currentTimeInMillis;
  }

  /**
   * Sends an HTTP POST request with JSON payload.
   *
   * @param string $url
   *   The endpoint URL.
   * @param array $fields
   *   The request payload.
   * @param array|null $http_header_array
   *   Optional request headers.
   *
   * @return string
   *   The response body.
   */
  public function makeHttpClientCall($url, $fields, $http_header_array = NULL) {
    if ($http_header_array === NULL) {
      $http_header_array = [
        'Content-Type' => 'application/json',
        'charset' => 'UTF-8',
        'Authorization' => 'Basic',
      ];
    }

    $response = $this->httpClient->post($url, [
      'headers' => $http_header_array,
      'body' => json_encode($fields),
    ]);
    return $response->getBody()->getContents();
  }

}
