<?php

namespace Drupal\user_provisioning\ProviderSpecific\ResponseProcessor\UserResponseProcessor;

use Drupal\Component\Serialization\Json;
use Drupal\user_provisioning\Helpers\moUserProvisioningLogger;
use Drupal\user_provisioning\moUserProvisioningConstants;
use Drupal\user_provisioning\ProviderSpecific\ResponseProcessor\moResourceResponseProcessorInterface;
use Psr\Http\Message\ResponseInterface;

/**
 * Processes user API responses returned by Azure AD.
 */
class moUserAzureResponseProcessor implements moResourceResponseProcessorInterface {

  /**
   * Logger for response processing diagnostics.
   *
   * @var \Drupal\user_provisioning\Helpers\moUserProvisioningLogger
   *   Logger instance.
   */
  private moUserProvisioningLogger $moLogger;

  public function __construct() {
    $this->moLogger = new moUserProvisioningLogger();
  }

  /**
   * {@inheritDoc}
   */
  public function get(ResponseInterface $response) {
    $status_code = $response->getStatusCode();
    $content = $response->getBody()->getContents();
    $content_val = Json::decode($content);
    $user = $content_val['value'];

    // Initializing as conflict is not determined.
    $conflict = moUserProvisioningConstants::AZURE_CONFLICT_UNDETERMINED;
    if ($status_code == 200) {
      if (empty($user)) {
        // No conflict exists if no matching entity is found.
        $conflict = moUserProvisioningConstants::AZURE_NO_CONFLICT;
        $this->moLogger->addLog('No matching user found, setting conflict status to AZURE_NO_CONFLICT.', __LINE__, __FUNCTION__, __FILE__);
      }
      else {
        // Conflict exists when one or more entities match the requested query.
        $conflict = moUserProvisioningConstants::AZURE_CONFLICT;
        $this->moLogger->addLog('User found, setting conflict status to AZURE_CONFLICT.', __LINE__, __FUNCTION__, __FILE__);
      }
    }
    return [$status_code, $content, $conflict];
  }

  /**
   * {@inheritDoc}
   */
  public function post(ResponseInterface $response) {
    $status_code = $response->getStatusCode();
    $content = $response->getBody()->getContents();
    return [$status_code, $content];
  }

  /**
   * {@inheritDoc}
   */
  public function patch(ResponseInterface $response) {
    // @todo Implement patch() method.
  }

  /**
   * {@inheritDoc}
   */
  public function put(ResponseInterface $response) {
    // @todo Implement put() method.
  }

  /**
   * {@inheritDoc}
   */
  public function delete(ResponseInterface $response) {
    // @todo Implement delete() method.
  }

  /**
   * {@inheritDoc}
   */
  public function deactivate(ResponseInterface $response) {
    // @todo Implement deactivate() method.
  }

}
