<?php

namespace Drupal\user_provisioning\ProviderSpecific\APIHandler\UserAPIHandler;

use Drupal\Core\Config\ImmutableConfig;
use Drupal\user_provisioning\Helpers\moUserProvisioningLogger;
use Drupal\user_provisioning\ProviderSpecific\APIHandler\moAPIHandlerInterface;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;
use Psr\Log\LoggerInterface;

/**
 *
 */
class moUserOktaAPIHandler implements moAPIHandlerInterface {
  private string $server_url;
  private string $bearer_token;
  private Client $http_client;
  private ImmutableConfig $config;
  private LoggerInterface $logger;
  private moUserProvisioningLogger $mo_logger;

  /**
   *
   */
  public function __construct() {
    $this->config = \Drupal::config('user_provisioning.settings');
    $this->server_url = $this->config->get('mo_provider_specific_provisioning_base_url');
    $this->bearer_token = $this->config->get('mo_provider_specific_provisioning_api_token');
    $this->http_client = \Drupal::httpClient();
    $this->logger = \Drupal::logger('user_provisioning');
    $this->mo_logger = new moUserProvisioningLogger();
  }

  /**
   *
   */
  public static function show_error_message($get) {
    echo '<div style="font-family:Calibri;padding:0 3%;">
            <div style="color: #a94442;background-color: #f2dede;padding: 15px;margin-bottom: 20px;text-align:center;border:1px solid #E6B3B2;font-size:18pt;">
            ERROR
            </div><div style="color: #a94442;font-size:14pt; margin-bottom:20px;">';

    foreach ($get as $key => $val) {
      if ($key == 'state') {
        continue;
      }
      echo '<p><strong>' . $key . ': </strong>' . $val . '</p>';
    }
    echo '</div></div>';
    exit;
  }

  /**
   *
   */
  public function get($query) {
    $url = $this->getRequestURL($query);
    $options = ['headers' => ['Authorization' => 'SSWS ' . $this->bearer_token], 'verify' => FALSE];

    $this->mo_logger->addLog('Query url is ' . $url, __LINE__, __FUNCTION__, __FILE__);
    $this->mo_logger->addFormattedLog($options, __LINE__, __FUNCTION__, __FILE__, 'The header for resource search request is:');
    try {
      return $this->http_client->get($url, $options);
    }
    catch (\Exception $exception) {
      // 409 conflict should be handled through the catch statement.
      throw new \Exception($exception->getMessage(), $exception->getCode(), $exception);
    }
  }

  /**
   *
   */
  public function post(array $body) {
    $header = [
      'Accept' => 'application/json',
      'Authorization' => 'SSWS ' . $this->bearer_token,
      'Content-Type' => 'application/json',
    ];

    $url = $this->postRequestURL();
    $options = [
      'headers' => $header,
      'body' => json_encode($body),
      'verify' => FALSE,
    ];

    $this->mo_logger->addLog('Query url is ' . $url, __LINE__, __FUNCTION__, __FILE__);
    $this->mo_logger->addFormattedLog($options, __LINE__, __FUNCTION__, __FILE__, 'The header and body for resource creation request is:');

    try {
      return $this->http_client->request(
        'POST',
        $url,
        $options,
      );
    }
    catch (GuzzleException $exception) {
      throw new \Exception($exception->getMessage(), $exception->getCode(), $exception);
    }

  }

  /**
   *
   */
  private function getRequestURL($query): string {
    return rtrim($this->server_url, '/') . '/' . 'api' . '/' . 'v1' . '/' . $query;
  }

  /**
   * Creates and returns the URL to make POST api call for user creation.
   *
   * @return string
   */
  private function postRequestURL(): string {
    return rtrim($this->server_url, '/') . '/api/v1/users?activate=false';
  }

  /**
   *
   */
  private function deactivateUserURL($query): string {
    return rtrim($this->server_url, '/') . '/api/v1/users/' . $query . '/lifecycle/deactivate';
  }

  /**
   *
   */
  public function put(array $body) {
    // @todo Implement put() method.
  }

  /**
   *
   */
  public function patch(array $patch) {
    // @todo Implement patch() method.
  }

  /**
   *
   */
  public function delete($resource_id) {
    // @todo Implement delete() method.
  }

  /**
   *
   */
  public function deactivate(array $body) {
    $header = [
      'Accept' => 'application/json',
      'Authorization' => 'SSWS ' . $this->bearer_token,
      'Content-Type' => 'application/json',
    ];

    $url = $this->deactivateUserURL($body[0]);
    $options = [
      'headers' => $header,
      'body' => NULL,
      'verify' => FALSE,
    ];

    $this->mo_logger->addLog('Query url is ' . $url, __LINE__, __FUNCTION__, __FILE__);
    $this->mo_logger->addFormattedLog($options, __LINE__, __FUNCTION__, __FILE__, 'The header and body for resource deactivation request is:');

    try {
      return $this->http_client->request(
        'POST',
        $url,
        $options,
      );
    }
    catch (GuzzleException $exception) {
      throw new \Exception($exception->getMessage(), $exception->getCode(), $exception);
    }
  }

}
