<?php

namespace Drupal\acquia_contenthub\Libs\Traits;

use Acquia\ContentHubClient\StatusCodes;
use Psr\Http\Message\ResponseInterface;
use Symfony\Bridge\PsrHttpMessage\Factory\HttpFoundationFactory;

/**
 * Encapsulates common helper functions for response checks.
 */
trait ResponseCheckerTrait {

  /**
   * Checks if the response was successful.
   *
   * @param \Psr\Http\Message\ResponseInterface|null $response
   *   The response.
   *
   * @return bool
   *   True if the response returned with 2xx status code.
   */
  protected function isSuccessful(?ResponseInterface $response): bool {
    if (is_null($response)) {
      return FALSE;
    }

    return (new HttpFoundationFactory())
      ->createResponse($response)
      ->isSuccessful();
  }

  /**
   * Checks if the response array is successful.
   *
   * @param array|null $response
   *   The response.
   *
   * @return bool
   *   True if the response is successful.
   */
  protected function isResponseSuccessful(?array $response): bool {
    if (is_null($response)) {
      return FALSE;
    }

    if (!isset($response['success']) || $response['success'] === FALSE) {
      return FALSE;
    }
    return TRUE;
  }

  /**
   * Checks for maintenance error.
   *
   * @param \Psr\Http\Message\ResponseInterface|null $response
   *   The response to check.
   *
   * @return bool
   *   TRUE if the service is in maintenance mode.
   */
  protected function isMaintenanceError(?ResponseInterface $response): bool {
    if (is_null($response)) {
      return FALSE;
    }

    $body = json_decode($response->getBody(), TRUE);
    $status_code = $body['error']['code'] ?? FALSE;
    return $status_code === StatusCodes::SERVICE_UNDER_MAINTENANCE;
  }

}
