<?php

class Eurostocks_Request {

  public $username;
  public $password;
  public $api_key;
  public $api_host;
  public $lang;

  public function __construct($username, $password, $api_key){
    $this->username = $username;
    $this->password = $password;
    $this->api_key  = $api_key;
    $this->api_host  = "https://services.eurostocks.com";
    $this->lang  = "nl";
  }

  private function eurostocks_should_log_errors() {
    return defined( 'WP_DEBUG_LOG' ) && WP_DEBUG_LOG;
  }

  private function eurostocks_normalize_log_value( $value ) {
    if ( is_array( $value ) ) {
      foreach ( $value as $key => $item ) {
        $value[ $key ] = $this->eurostocks_normalize_log_value( $item );
      }

      return $value;
    }

    if ( is_string( $value ) ) {
      return str_replace( array( "\r", "\n" ), ' ', $value );
    }

    return $value;
  }

  private function eurostocks_log_api_error($channel, $message, $context = array()) {
    if ( ! $this->eurostocks_should_log_errors() ) {
      return;
    }

    $message = $this->eurostocks_normalize_log_value( $message );

    $context_string = '';
    if ( ! empty( $context ) ) {
      $context_string = ' ' . wp_json_encode( $this->eurostocks_normalize_log_value( $context ) );
    }

    $channel = sanitize_text_field( (string) $channel );
    if ( '' === $channel ) {
      $channel = 'API';
    }

    $log_message = str_replace( array( "\r", "\n" ), ' ', '[Eurostocks ' . $channel . '] ' . $message . $context_string );

    error_log( $log_message ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log
  }

  private function eurostocks_log_models_error($message, $context = array()) {
    $this->eurostocks_log_api_error( 'Models', $message, $context );
  }

  private function eurostocks_log_vehicle_list_error($message, $context = array()) {
    $this->eurostocks_log_api_error( 'Vehicle List', $message, $context );
  }

  private function eurostocks_limit_log_string($value, $limit = 300) {
    if ( ! is_string( $value ) || '' === $value ) {
      return '';
    }

    $value = wp_strip_all_tags( $value );

    if ( function_exists( 'mb_substr' ) ) {
      return mb_substr( $value, 0, $limit );
    }

    return substr( $value, 0, $limit );
  }

  private function eurostocks_build_vehicle_list_log_context( $args, $extra = array() ) {
    $context = array(
      'page_number' => isset( $args['pagenumber'] ) ? (int) $args['pagenumber'] : 0,
      'language'    => isset( $args['language_iso_code'] ) ? sanitize_text_field( $args['language_iso_code'] ) : '',
      'make'        => isset( $args['make'] ) ? sanitize_text_field( $args['make'] ) : '',
      'model'       => isset( $args['model'] ) ? sanitize_text_field( $args['model'] ) : '',
      'model_group' => isset( $args['model_group'] ) ? sanitize_text_field( $args['model_group'] ) : '',
      'sort_on'     => isset( $args['sort_on'] ) ? sanitize_text_field( $args['sort_on'] ) : '',
    );

    if ( ! empty( $extra ) ) {
      $context = array_merge( $context, $extra );
    }

    return $context;
  }

  public function get_api_statistics($from_date, $to_date) {
    $url = "/api/v1/statistics/apiStatistics/" . $from_date . "/" . $to_date;
    $args = [
      'timeout' => 20,
      'headers' => array(
        'UserName' => $this->username,
        'Password' => $this->password,
        'APIKey'   => $this->api_key,
      ),
    ];

    $response = wp_remote_get($this->api_host . $url, $args);
    if ( is_wp_error( $response ) ) {
        return $response;
    }

    $status_code = wp_remote_retrieve_response_code( $response );
    $body = wp_remote_retrieve_body( $response );
    $result = json_decode( $body, true );

    if ( ($status_code >= 200 && $status_code < 300) && is_array( $result ) ) {
        return $result;
    }

    $message = __( 'Unable to fetch API statistics.', 'eurostocks' );
    if ( 401 === $status_code || 403 === $status_code ) {
        $message = __( 'We are currently unable to display the API statistics because you do not (yet) have access. Would you like to see this? Please contact Eurostocks and we will be happy to help.', 'eurostocks' );
    }

    return new WP_Error(
        'api_statistics_failed',
        $message,
        array(
            'status_code' => $status_code,
            'body'        => $body,
        )
    );
  }

  public function getVehicleMakes(){
    $url = "/api/v2/import/car/import/makes";
    $args = [
      'timeout' => 10,
      'headers' => array(
        'UserName' => $this->username,
        'Password' => $this->password,
        'APIKey'   => $this->api_key,
        'Content-Type' => 'application/json',
      )
    ];
    $response = wp_remote_get($this->api_host . $url, $args);

    if ( is_wp_error( $response ) ) {
        $error_message = $response->get_error_message();
        return $error_message;
    }
    $responseBody = wp_remote_retrieve_body( $response );

    $result = json_decode( $responseBody, true );

    if ( is_array( $result ) && ! is_wp_error( $result ) ) {
        return $result;
    } else {
        return false;
    }
  }

    public function getTransmissions($lang){
      $url = "/api/v2/import/car/import/transmissions/" . $lang;
      $args = [
        'timeout' => 10,
        'headers' => array(
          'UserName' => $this->username,
          'Password' => $this->password,
          'APIKey'   => $this->api_key,
          'Content-Type' => 'application/json',
        )
      ];
      $response = wp_remote_get($this->api_host . $url, $args);

      if ( is_wp_error( $response ) ) {
          $error_message = $response->get_error_message();
          return $error_message;
      }
      $responseBody = wp_remote_retrieve_body( $response );
      $result = json_decode( $responseBody, true );

      if ( is_array( $result ) && ! is_wp_error( $result ) ) {
          return $result;
      } else {
          return false;
      }
    }

    public function getCategories($lang){
      $url = "/api/v2/import/car/import/categories/" . $lang;
      $args = [
        'timeout' => 10,
        'headers' => array(
          'UserName' => $this->username,
          'Password' => $this->password,
          'APIKey'   => $this->api_key,
          'Content-Type' => 'application/json',
        )
      ];
      $response = wp_remote_get($this->api_host . $url, $args);

      if ( is_wp_error( $response ) ) {
          $error_message = $response->get_error_message();
          return $error_message;
      }
      $responseBody = wp_remote_retrieve_body( $response );

      $result = json_decode( $responseBody, true );
      if ( is_array( $result ) && ! is_wp_error( $result ) ) {
          return $result;
      } else {
          return false;
      }
    }

    public function getHeadlightTypes($lang){
      $url = "/api/v2/import/car/import/headlightTypes/" . $lang;
      $args = [
        'timeout' => 10,
        'headers' => array(
          'UserName' => $this->username,
          'Password' => $this->password,
          'APIKey'   => $this->api_key,
          'Content-Type' => 'application/json',
        )
      ];
      $response = wp_remote_get($this->api_host . $url, $args);

      if ( is_wp_error( $response ) ) {
          $error_message = $response->get_error_message();
          return $error_message;
      }
      $responseBody = wp_remote_retrieve_body( $response );

      $result = json_decode( $responseBody, true );
      if ( is_array( $result ) && ! is_wp_error( $result ) ) {
          return $result;
      } else {
          return false;
      }
    }

    public function getFuelTypes($lang){
      $url = "/api/v2/import/car/import/fueltypes/" . $lang;
      $args = [
        'timeout' => 10,
        'headers' => array(
          'UserName' => $this->username,
          'Password' => $this->password,
          'APIKey'   => $this->api_key,
          'Content-Type' => 'application/json',
        )
      ];
      $response = wp_remote_get($this->api_host . $url, $args);

      if ( is_wp_error( $response ) ) {
          $error_message = $response->get_error_message();
          return $error_message;
      }
      $responseBody = wp_remote_retrieve_body( $response );

      $result = json_decode( $responseBody, true );
      if ( is_array( $result ) && ! is_wp_error( $result ) ) {
          return $result;
      } else {
          return false;
      }
    }

    public function getDoorCounts($lang){
      $url = "/api/v2/import/car/import/doorCounts/" . $lang;
      $args = [
        'timeout' => 10,
        'headers' => array(
          'UserName' => $this->username,
          'Password' => $this->password,
          'APIKey'   => $this->api_key,
          'Content-Type' => 'application/json',
        )
      ];
      $response = wp_remote_get($this->api_host . $url, $args);

      if ( is_wp_error( $response ) ) {
          $error_message = $response->get_error_message();
          return $error_message;
      }
      $responseBody = wp_remote_retrieve_body( $response );

      $result = json_decode( $responseBody, true );
      if ( is_array( $result ) && ! is_wp_error( $result ) ) {
          return $result;
      } else {
          return false;
      }
    }

    public function getExteriorColors($lang){
      $url = "/api/v2/import/car/import/exteriorColors/" . $lang;
      $args = [
        'timeout' => 10,
        'headers' => array(
          'UserName' => $this->username,
          'Password' => $this->password,
          'APIKey'   => $this->api_key,
          'Content-Type' => 'application/json',
        )
      ];
      $response = wp_remote_get($this->api_host . $url, $args);

      if ( is_wp_error( $response ) ) {
          $error_message = $response->get_error_message();
          return $error_message;
      }
      $responseBody = wp_remote_retrieve_body( $response );

      $result = json_decode( $responseBody, true );
      if ( is_array( $result ) && ! is_wp_error( $result ) ) {
          return $result;
      } else {
          return false;
      }
    }

    public function getClimatisations($lang){
      $url = "/api/v2/import/car/import/climatisations/" . $lang;
      $args = [
        'timeout' => 10,
        'headers' => array(
          'UserName' => $this->username,
          'Password' => $this->password,
          'APIKey'   => $this->api_key,
          'Content-Type' => 'application/json',
        )
      ];
      $response = wp_remote_get($this->api_host . $url, $args);

      if ( is_wp_error( $response ) ) {
          $error_message = $response->get_error_message();
          return $error_message;
      }
      $responseBody = wp_remote_retrieve_body( $response );

      $result = json_decode( $responseBody, true );
      if ( is_array( $result ) && ! is_wp_error( $result ) ) {
          return $result;
      } else {
          return false;
      }
    }

    public function getInteriorTypes($lang){
      $url = "/api/v2/import/car/import/interiorTypes/" . $lang;
      $args = [
        'timeout' => 10,
        'headers' => array(
          'UserName' => $this->username,
          'Password' => $this->password,
          'APIKey'   => $this->api_key,
          'Content-Type' => 'application/json',
        )
      ];
      $response = wp_remote_get($this->api_host . $url, $args);

      if ( is_wp_error( $response ) ) {
          $error_message = $response->get_error_message();
          return $error_message;
      }
      $responseBody = wp_remote_retrieve_body( $response );

      $result = json_decode( $responseBody, true );
      if ( is_array( $result ) && ! is_wp_error( $result ) ) {
          return $result;
      } else {
          return false;
      }
    }

    public function getParkingAssistant($lang){
      $url = "/api/v2/import/car/import/parkingAssistant/" . $lang;
      $args = [
        'timeout' => 10,
        'headers' => array(
          'UserName' => $this->username,
          'Password' => $this->password,
          'APIKey'   => $this->api_key,
          'Content-Type' => 'application/json',
        )
      ];
      $response = wp_remote_get($this->api_host . $url, $args);

      if ( is_wp_error( $response ) ) {
          $error_message = $response->get_error_message();
          return $error_message;
      }
      $responseBody = wp_remote_retrieve_body( $response );

      $result = json_decode( $responseBody, true );
      if ( is_array( $result ) && ! is_wp_error( $result ) ) {
          return $result;
      } else {
          return false;
      }
    }

    public function getSpeedControls($lang){
      $url = "/api/v2/import/car/import/speedControls/" . $lang;
      $args = [
        'timeout' => 10,
        'headers' => array(
          'UserName' => $this->username,
          'Password' => $this->password,
          'APIKey'   => $this->api_key,
          'Content-Type' => 'application/json',
        )
      ];
      $response = wp_remote_get($this->api_host . $url, $args);

      if ( is_wp_error( $response ) ) {
          $error_message = $response->get_error_message();
          return $error_message;
      }
      $responseBody = wp_remote_retrieve_body( $response );

      $result = json_decode( $responseBody, true );
      if ( is_array( $result ) && ! is_wp_error( $result ) ) {
          return $result;
      } else {
          return false;
      }
    }



  public function getVehicleModels($makeKey){
    $url = "/api/v2/import/car/import/models/" . $makeKey;

    $args = [
      'headers' => array(
        'UserName' => $this->username,
        'Password' => $this->password,
        'APIKey'   => $this->api_key,
        'Content-Type' => 'application/json',
      ),
      'timeout' => 45
    ];
    $response = wp_remote_get($this->api_host . $url, $args);

    if ( is_wp_error( $response ) ) {
        $error_code = $response->get_error_code();
        $error_message = $response->get_error_message();
        $normalized = strtolower($error_message);

        $this->eurostocks_log_models_error(
          'Model request failed before a response was received.',
          array(
            'make_key' => sanitize_text_field( $makeKey ),
            'error_code' => $error_code,
            'error_message' => $error_message,
          )
        );

        // Provide a friendly message for timeouts without technical details
        if (
          $error_code === 'http_request_timed_out' ||
          $error_code === 'timeout' ||
          strpos($normalized, 'timed out') !== false ||
          strpos($normalized, 'operation timed out') !== false ||
          strpos($normalized, 'curl error 28') !== false
        ) {
          return __( 'The request took too long. Please try again shortly.', 'eurostocks' );
        }

        return __( 'The request could not be completed right now. Please try again shortly.', 'eurostocks' );
    }
    $status_code = wp_remote_retrieve_response_code( $response );
    $responseBody = wp_remote_retrieve_body( $response );
    $result = json_decode( $responseBody, true );

    if ( $status_code < 200 || $status_code >= 300 ) {
        $this->eurostocks_log_models_error(
          'Model request returned a non-success status code.',
          array(
            'make_key' => sanitize_text_field( $makeKey ),
            'status_code' => $status_code,
            'response_body' => $this->eurostocks_limit_log_string( $responseBody ),
          )
        );
        if ( 429 === $status_code ) {
            return new WP_Error( 'rate_limited', __( 'Too many requests. Please try again later.', 'eurostocks' ) );
        }
        return __( 'There was an issue retrieving the models.', 'eurostocks' );
    }

    if ( is_array( $result ) ) {
        return $result;
    }

    $this->eurostocks_log_models_error(
      'Model request returned an unexpected response payload.',
      array(
        'make_key' => sanitize_text_field( $makeKey ),
        'status_code' => $status_code,
        'response_body' => $this->eurostocks_limit_log_string( $responseBody ),
      )
    );

    return __( 'There was an issue retrieving the models.', 'eurostocks' );

  }

  public function getVehicleDetails($vehicleId, $lang){
    $url = "/api/v2/import/detail/" . $vehicleId . "?languageIsoCode=" . $lang;

    $args = [
      'headers' => array(
        'UserName' => $this->username,
        'Password' => $this->password,
        'APIKey'   => $this->api_key,
      ),
      'timeout' => 10
    ];
    $response = wp_remote_get($this->api_host . $url, $args);
    
    $response_code = wp_remote_retrieve_response_code($response);
    if($response_code == 429){
      return 429;
    }
    if($response_code == 404){
      return 404;
    }
    if ( is_wp_error( $response ) ) {
        $error_message = $response->get_error_message();
        return $error_message;
    }
    $responseBody = wp_remote_retrieve_body( $response );
    
    $result = json_decode( $responseBody, true );
    if ( is_array( $result ) && ! is_wp_error( $result ) ) {
        return $result;
    } else {
      $error_message = $result;
      return $error_message;
    }

  }

  public function getVehicleList($args){
    $body = array();

    $body['pageNumber'] = intval($args["pagenumber"]);
    $body['languageIsoCode'] = $args["language_iso_code"];

    if(isset($args["exterior_color"]) && $args["exterior_color"] != ''){
      $body['exteriorColor'] = $args["exterior_color"];
    }
    if(isset($args["door_count"]) && $args["door_count"] != ''){
      $body['doorCount'] = $args["door_count"];
    }
    if(isset($args["vat"]) && $args["vat"] != ''){
      if($args["vat"] == 'ja'){
        $body['vatable'] = 'true';
      }
      if($args["vat"] == 'nee'){
        $body['vatable'] = 'false';
      }
    }
    if(isset($args["headlight_type"]) && $args["headlight_type"] != ''){
      $body['headlightType'] = $args["headlight_type"];
    }
    if(isset($args["climatisation"]) && $args["climatisation"] != ''){
      $body['climatisation'] = $args["climatisation"];
    }
   
    if(isset($args["interior_type"]) && $args["interior_type"] != ''){
      $body['interiorType'] = $args["interior_type"];
    }
    if(isset($args["speed_control"]) && $args["speed_control"] != ''){
      $body['speedControl'] = $args["speed_control"];
    }
    if(isset($args["transmission"]) && $args["transmission"] != ''){
      if($args['transmission'] == 'AUTOMATIC_GEAR' || $args['transmission'] == 'SEMIAUTOMATIC_GEAR'){
        $body['transmission'] = "AUTOMATIC_GEAR,SEMIAUTOMATIC_GEAR";
      }else{
        $body['transmission'] = $args["transmission"];
      }
    }
    if(isset($args["fuel_type"]) && $args["fuel_type"] != ''){
      $body['fuelType'] = $args["fuel_type"];
    }
    if(isset($args["category"]) && $args["category"] != ''){
      $body['category'] = $args["category"];
    }

    if(isset($args["drive_type"]) && $args["drive_type"] != ''){
      $body['driveType'] = $args["drive_type"];
    }

    if(isset($args["make"]) && $args["make"] != ''){
      $body['make'] = $args["make"];
    }
    $radio = array();
    if(isset($args["feature"]) && !empty($args["feature"])){
      
      // check if TUNER or DAB_RADIO is in the array
      if(in_array('TUNER_RADIO', $args["feature"])){
        $key = array_search('TUNER_RADIO', $args["feature"]);
        unset($args["feature"][$key]);
        array_push($radio, 'TUNER');
      }
      if(in_array('DAB_RADIO', $args["feature"])){
        $key = array_search('DAB_RADIO', $args["feature"]);
        unset($args["feature"][$key]);      
        array_push($radio, 'DAB_RADIO');
      }

      if(in_array('TRAILER_COUPLING', $args["feature"])){
        $key = array_search('TRAILER_COUPLING', $args["feature"]);
        unset($args["feature"][$key]);
        $body['trailerCouplingType'] = "TRAILER_COUPLING_FIX,TRAILER_COUPLING_SWIVELING,TRAILER_COUPLING_DETACHABLE";
      }

      $features = implode(',', $args["feature"]);
      if($features != ''){
        $body['feature'] = $features;
      }
    }

    if(isset($radio) && !empty($radio)){
      if(in_array('TUNER', $radio) && in_array('DAB_RADIO', $radio)){
        $radio = array_diff($radio, array('TUNER'));
      
      }
      $radio_string = implode(',', $radio);
      $body['radio'] = $radio_string;
    }

    if(isset($args["parking_assistant"]) && !empty($args["parking_assistant"])){
      $parking_assistant = implode(',', $args["parking_assistant"]);
      $body['parkingAssistant'] = $parking_assistant;
    }

    if(isset($args["customer_id"]) && $args["customer_id"] != ''){
      $body['customerId'] = $args["customer_id"];
    }

    if(isset($args["number_of_previous_owners_max"]) && $args["number_of_previous_owners_max"] == 1){
      $body['numberOfPreviousOwnersMax'] = 1;
    }

    if(isset($args["is_accident_damaged"]) && $args["is_accident_damaged"] === false){
      $body['isAccidentDamaged'] = 'false';
    }

    if(isset($args["model"]) && $args["model"] != ''){
      $body['model'] = $args["model"];
    }
    if(isset($args["model_group"]) && $args["model_group"] != ''){
      $body['modelGroup'] = $args["model_group"];
    }
    if(isset($args["year_to"]) && $args["year_to"] != ''){
      $body['yearTo'] = intval($args["year_to"]);
    }
    if(isset($args["year_from"]) && $args["year_from"] != ''){
      $body['yearFrom'] = intval($args["year_from"]);
      if(!isset($args["year_to"]) || $args["year_to"] == ''){
        $body['yearTo'] = 2025;
      }
    }

    if(isset($args["mileage_from"]) && $args["mileage_from"] != ''){
      $body['mileageMin'] = intval($args["mileage_from"]);
    }
    if(isset($args["mileage_to"]) && $args["mileage_to"] != ''){
      $body['mileageMax'] = intval($args["mileage_to"]);
    }
    if(isset($args["power_from"]) && $args["power_from"] != ''){
      $body['powerMin'] = intval($args["power_from"]);

      if(!isset($args["power_to"]) || $args["power_to"] == ''){
        $body['powerMax'] = 999;
      }
    }

    if(isset($args["seats_count"]) && $args["seats_count"] != ''){
      $body['numSeatsMin'] = intval($args["seats_count"]);
    }
    if(isset($args["power_to"]) && $args["power_to"] != ''){
      $body['powerMax'] = intval($args["power_to"]);
    }
    if(isset($args["price_from"]) && $args["price_from"] != ''){
      $body['priceFrom'] = intval($args["price_from"]);
    }
    if(isset($args["price_to"]) && $args["price_to"] != ''){
      $body['priceTo'] = intval($args["price_to"]);
    }

    if(isset($args["sort_on"]) && $args["sort_on"] != ''){
      if($args["sort_on"] == 'priceDesc'){
        $body['sortOn'] = 'price';
        $body['sortOrder'] = 'descending';
      }elseif($args["sort_on"] == 'priceAsc'){
        $body['sortOn'] = 'price';
        $body['sortOrder'] = 'ascending';
      }elseif($args["sort_on"] == 'mileageDesc'){
        $body['sortOn'] = 'mileage';
        $body['sortOrder'] = 'descending';
      }elseif($args["sort_on"] == 'mileageAsc'){
        $body['sortOn'] = 'mileage';
        $body['sortOrder'] = 'ascending';
      }elseif($args["sort_on"] == 'registrationAsc'){
        $body['sortOn'] = 'firstRegistrationDate';
        $body['sortOrder'] = 'ascending';
      }elseif($args["sort_on"] == 'registrationDesc'){
        $body['sortOn'] = 'firstRegistrationDate';
        $body['sortOrder'] = 'descending';
      }elseif($args["sort_on"] == 'creationAsc'){
        $body['sortOn'] = 'creationTime';
        $body['sortOrder'] = 'ascending';
      }elseif($args["sort_on"] == 'creationDesc'){
        $body['sortOn'] = 'creationTime';
        $body['sortOrder'] = 'descending';
      }else{
        $body['sortOn'] = 'price';
        $body['sortOrder'] = 'ascending';
      }
    }else{
      $body['sortOn'] = 'creationTime';
      $body['sortOrder'] = 'descending';
    }
   
    $url = "/api/v2/import/list";
    $response = wp_remote_post( $this->api_host . $url, array(
        'method'      => 'POST',
        'timeout'     => 45,
        'redirection' => 1,
        'httpversion' => '1.0',
        'blocking'    => true,
        'headers'     => [
          'UserName' => $this->username,
          'Password'    => $this->password,
          'APIKey'  => $this->api_key
        ],
        'body'        => $body,
        'data_format' => 'body',
        )
    );
    $response_code = wp_remote_retrieve_response_code($response);
    if($response_code == 429){
      $this->eurostocks_log_vehicle_list_error(
        'Vehicle list request returned a rate limit response.',
        $this->eurostocks_build_vehicle_list_log_context(
          $args,
          array(
            'status_code' => $response_code,
          )
        )
      );
      return 429;
    }
    if ( is_wp_error( $response ) ) {
        $this->eurostocks_log_vehicle_list_error(
          'Vehicle list request failed before a response was received.',
          $this->eurostocks_build_vehicle_list_log_context(
            $args,
            array(
              'error_code'    => $response->get_error_code(),
              'error_message' => $response->get_error_message(),
            )
          )
        );

        return $response->get_error_message();
    } else {
      if ( $response_code < 200 || $response_code >= 300 ) {
        $this->eurostocks_log_vehicle_list_error(
          'Vehicle list request returned a non-success status code.',
          $this->eurostocks_build_vehicle_list_log_context(
            $args,
            array(
              'status_code'   => $response_code,
              'response_body' => $this->eurostocks_limit_log_string( wp_remote_retrieve_body( $response ) ),
            )
          )
        );
      }

      $responseBody = wp_remote_retrieve_body( $response );
      $result = json_decode( $responseBody, true );

      if ( ! is_array( $result ) ) {
        $this->eurostocks_log_vehicle_list_error(
          'Vehicle list request returned an unexpected response payload.',
          $this->eurostocks_build_vehicle_list_log_context(
            $args,
            array(
              'status_code'   => $response_code,
              'response_body' => $this->eurostocks_limit_log_string( $responseBody ),
            )
          )
        );
      } elseif ( ! isset( $result['vehicles'] ) && ! isset( $result['Status'] ) ) {
        $this->eurostocks_log_vehicle_list_error(
          'Vehicle list response is missing the expected vehicles payload.',
          $this->eurostocks_build_vehicle_list_log_context(
            $args,
            array(
              'status_code' => $response_code,
              'keys'        => array_keys( $result ),
            )
          )
        );
      }

      return $result;

    }

  }

}
