<?php

namespace Drupal\user_provisioning\ProviderSpecific\ResponseProcessor\UserResponseProcessor;

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 Keycloak.
 */
class moUserKeycloakResponseProcessor implements moResourceResponseProcessorInterface {

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

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

  /**
   * Processes Keycloak GET user-search responses.
   */
  public function get(ResponseInterface $response) {
    $status_code = $response->getStatusCode();
    $content = $response->getBody()->getContents();
    $conflict = moUserProvisioningConstants::KEYCLOAK_CONFLICT_UNDETERMINED;
    if ($status_code == 200) {
      $response = json_decode($content, TRUE);
      $user_id = NULL;
      if (isset($response[0]['id'])) {
        $user_id = $response[0]['id'];
      }

      if (is_null($user_id)) {
        $conflict = moUserProvisioningConstants::KEYCLOAK_NO_CONFLICT;
        $this->moLogger->addLog('No matching user found, setting conflict status to KEYCLOAK_NO_CONFLICT.', __LINE__, __FUNCTION__, __FILE__);
      }
      else {
        $conflict = moUserProvisioningConstants::KEYCLOAK_CONFLICT;
        $this->moLogger->addLog('User found, setting conflict status to KEYCLOAK_CONFLICT.', __LINE__, __FUNCTION__, __FILE__);
      }
    }
    return [$status_code, $content, $conflict];
  }

  /**
   * Processes Keycloak POST responses.
   */
  public function post(ResponseInterface $response) {
    $status_code = $response->getStatusCode();
    $content = $response->getBody()->getContents();
    return [$status_code, $content];
  }

  /**
   * Processes Keycloak PATCH responses.
   */
  #[\Override] public function patch(ResponseInterface $response) {
    // @todo Implement patch() method.
  }

  /**
   * Processes Keycloak PUT responses.
   */
  #[\Override] public function put(ResponseInterface $response) {
    // @todo Implement put() method.
  }

  /**
   * Processes Keycloak DELETE responses.
   */
  #[\Override] public function delete(ResponseInterface $response) {
    // @todo Implement delete() method.
  }

  /**
   * Processes Keycloak deactivation responses.
   */
  #[\Override] public function deactivate(ResponseInterface $response) {
    // @todo Implement deactivate() method.
  }

}
