/*
 * Binance VIP Loan REST API
 *
 * OpenAPI Specification for the Binance VIP Loan REST API
 *
 * The version of the OpenAPI document: 1.0.0
 *
 *
 * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
 * https://openapi-generator.tech
 * Do not edit the class manually.
 */

#![allow(unused_imports)]
use async_trait::async_trait;
use derive_builder::Builder;
use reqwest;
use rust_decimal::prelude::*;
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use std::collections::BTreeMap;

use crate::common::{
    config::ConfigurationRestApi,
    models::{ParamBuildError, RestApiResponse},
    utils::send_request,
};
use crate::vip_loan::rest_api::models;

const HAS_TIME_UNIT: bool = false;

#[async_trait]
pub trait MarketDataApi: Send + Sync {
    async fn get_borrow_interest_rate(
        &self,
        params: GetBorrowInterestRateParams,
    ) -> anyhow::Result<RestApiResponse<Vec<models::GetBorrowInterestRateResponseInner>>>;
    async fn get_collateral_asset_data(
        &self,
        params: GetCollateralAssetDataParams,
    ) -> anyhow::Result<RestApiResponse<models::GetCollateralAssetDataResponse>>;
    async fn get_loanable_assets_data(
        &self,
        params: GetLoanableAssetsDataParams,
    ) -> anyhow::Result<RestApiResponse<models::GetLoanableAssetsDataResponse>>;
    async fn get_vip_loan_interest_rate_history(
        &self,
        params: GetVipLoanInterestRateHistoryParams,
    ) -> anyhow::Result<RestApiResponse<models::GetVipLoanInterestRateHistoryResponse>>;
}

#[derive(Debug, Clone)]
pub struct MarketDataApiClient {
    configuration: ConfigurationRestApi,
}

impl MarketDataApiClient {
    pub fn new(configuration: ConfigurationRestApi) -> Self {
        Self { configuration }
    }
}

/// Request parameters for the [`get_borrow_interest_rate`] operation.
///
/// This struct holds all of the inputs you can pass when calling
/// [`get_borrow_interest_rate`](#method.get_borrow_interest_rate).
#[derive(Clone, Debug, Builder)]
#[builder(pattern = "owned", build_fn(error = "ParamBuildError"))]
pub struct GetBorrowInterestRateParams {
    ///
    /// The `loan_coin` parameter.
    ///
    /// This field is **required.
    #[builder(setter(into))]
    pub loan_coin: String,
    ///
    /// The `recv_window` parameter.
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub recv_window: Option<i64>,
}

impl GetBorrowInterestRateParams {
    /// Create a builder for [`get_borrow_interest_rate`].
    ///
    /// Required parameters:
    ///
    /// * `loan_coin` — String
    ///
    #[must_use]
    pub fn builder(loan_coin: String) -> GetBorrowInterestRateParamsBuilder {
        GetBorrowInterestRateParamsBuilder::default().loan_coin(loan_coin)
    }
}
/// Request parameters for the [`get_collateral_asset_data`] operation.
///
/// This struct holds all of the inputs you can pass when calling
/// [`get_collateral_asset_data`](#method.get_collateral_asset_data).
#[derive(Clone, Debug, Builder, Default)]
#[builder(pattern = "owned", build_fn(error = "ParamBuildError"))]
pub struct GetCollateralAssetDataParams {
    ///
    /// The `collateral_coin` parameter.
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub collateral_coin: Option<String>,
    ///
    /// The `recv_window` parameter.
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub recv_window: Option<i64>,
}

impl GetCollateralAssetDataParams {
    /// Create a builder for [`get_collateral_asset_data`].
    ///
    #[must_use]
    pub fn builder() -> GetCollateralAssetDataParamsBuilder {
        GetCollateralAssetDataParamsBuilder::default()
    }
}
/// Request parameters for the [`get_loanable_assets_data`] operation.
///
/// This struct holds all of the inputs you can pass when calling
/// [`get_loanable_assets_data`](#method.get_loanable_assets_data).
#[derive(Clone, Debug, Builder, Default)]
#[builder(pattern = "owned", build_fn(error = "ParamBuildError"))]
pub struct GetLoanableAssetsDataParams {
    ///
    /// The `loan_coin` parameter.
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub loan_coin: Option<String>,
    /// default:user's vip level
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub vip_level: Option<i64>,
    ///
    /// The `recv_window` parameter.
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub recv_window: Option<i64>,
}

impl GetLoanableAssetsDataParams {
    /// Create a builder for [`get_loanable_assets_data`].
    ///
    #[must_use]
    pub fn builder() -> GetLoanableAssetsDataParamsBuilder {
        GetLoanableAssetsDataParamsBuilder::default()
    }
}
/// Request parameters for the [`get_vip_loan_interest_rate_history`] operation.
///
/// This struct holds all of the inputs you can pass when calling
/// [`get_vip_loan_interest_rate_history`](#method.get_vip_loan_interest_rate_history).
#[derive(Clone, Debug, Builder)]
#[builder(pattern = "owned", build_fn(error = "ParamBuildError"))]
pub struct GetVipLoanInterestRateHistoryParams {
    ///
    /// The `coin` parameter.
    ///
    /// This field is **required.
    #[builder(setter(into))]
    pub coin: String,
    ///
    /// The `recv_window` parameter.
    ///
    /// This field is **required.
    #[builder(setter(into))]
    pub recv_window: i64,
    ///
    /// The `start_time` parameter.
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub start_time: Option<i64>,
    ///
    /// The `end_time` parameter.
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub end_time: Option<i64>,
    /// Current querying page. Start from 1; default: 1; max: 1000
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub current: Option<i64>,
    /// Default: 10; max: 100
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub limit: Option<i64>,
}

impl GetVipLoanInterestRateHistoryParams {
    /// Create a builder for [`get_vip_loan_interest_rate_history`].
    ///
    /// Required parameters:
    ///
    /// * `coin` — String
    /// * `recv_window` — i64
    ///
    #[must_use]
    pub fn builder(coin: String, recv_window: i64) -> GetVipLoanInterestRateHistoryParamsBuilder {
        GetVipLoanInterestRateHistoryParamsBuilder::default()
            .coin(coin)
            .recv_window(recv_window)
    }
}

#[async_trait]
impl MarketDataApi for MarketDataApiClient {
    async fn get_borrow_interest_rate(
        &self,
        params: GetBorrowInterestRateParams,
    ) -> anyhow::Result<RestApiResponse<Vec<models::GetBorrowInterestRateResponseInner>>> {
        let GetBorrowInterestRateParams {
            loan_coin,
            recv_window,
        } = params;

        let mut query_params = BTreeMap::new();
        let body_params = BTreeMap::new();

        query_params.insert("loanCoin".to_string(), json!(loan_coin));

        if let Some(rw) = recv_window {
            query_params.insert("recvWindow".to_string(), json!(rw));
        }

        send_request::<Vec<models::GetBorrowInterestRateResponseInner>>(
            &self.configuration,
            "/sapi/v1/loan/vip/request/interestRate",
            reqwest::Method::GET,
            query_params,
            body_params,
            if HAS_TIME_UNIT {
                self.configuration.time_unit
            } else {
                None
            },
            true,
        )
        .await
    }

    async fn get_collateral_asset_data(
        &self,
        params: GetCollateralAssetDataParams,
    ) -> anyhow::Result<RestApiResponse<models::GetCollateralAssetDataResponse>> {
        let GetCollateralAssetDataParams {
            collateral_coin,
            recv_window,
        } = params;

        let mut query_params = BTreeMap::new();
        let body_params = BTreeMap::new();

        if let Some(rw) = collateral_coin {
            query_params.insert("collateralCoin".to_string(), json!(rw));
        }

        if let Some(rw) = recv_window {
            query_params.insert("recvWindow".to_string(), json!(rw));
        }

        send_request::<models::GetCollateralAssetDataResponse>(
            &self.configuration,
            "/sapi/v1/loan/vip/collateral/data",
            reqwest::Method::GET,
            query_params,
            body_params,
            if HAS_TIME_UNIT {
                self.configuration.time_unit
            } else {
                None
            },
            true,
        )
        .await
    }

    async fn get_loanable_assets_data(
        &self,
        params: GetLoanableAssetsDataParams,
    ) -> anyhow::Result<RestApiResponse<models::GetLoanableAssetsDataResponse>> {
        let GetLoanableAssetsDataParams {
            loan_coin,
            vip_level,
            recv_window,
        } = params;

        let mut query_params = BTreeMap::new();
        let body_params = BTreeMap::new();

        if let Some(rw) = loan_coin {
            query_params.insert("loanCoin".to_string(), json!(rw));
        }

        if let Some(rw) = vip_level {
            query_params.insert("vipLevel".to_string(), json!(rw));
        }

        if let Some(rw) = recv_window {
            query_params.insert("recvWindow".to_string(), json!(rw));
        }

        send_request::<models::GetLoanableAssetsDataResponse>(
            &self.configuration,
            "/sapi/v1/loan/vip/loanable/data",
            reqwest::Method::GET,
            query_params,
            body_params,
            if HAS_TIME_UNIT {
                self.configuration.time_unit
            } else {
                None
            },
            true,
        )
        .await
    }

    async fn get_vip_loan_interest_rate_history(
        &self,
        params: GetVipLoanInterestRateHistoryParams,
    ) -> anyhow::Result<RestApiResponse<models::GetVipLoanInterestRateHistoryResponse>> {
        let GetVipLoanInterestRateHistoryParams {
            coin,
            recv_window,
            start_time,
            end_time,
            current,
            limit,
        } = params;

        let mut query_params = BTreeMap::new();
        let body_params = BTreeMap::new();

        query_params.insert("coin".to_string(), json!(coin));

        if let Some(rw) = start_time {
            query_params.insert("startTime".to_string(), json!(rw));
        }

        if let Some(rw) = end_time {
            query_params.insert("endTime".to_string(), json!(rw));
        }

        if let Some(rw) = current {
            query_params.insert("current".to_string(), json!(rw));
        }

        if let Some(rw) = limit {
            query_params.insert("limit".to_string(), json!(rw));
        }

        query_params.insert("recvWindow".to_string(), json!(recv_window));

        send_request::<models::GetVipLoanInterestRateHistoryResponse>(
            &self.configuration,
            "/sapi/v1/loan/vip/interestRateHistory",
            reqwest::Method::GET,
            query_params,
            body_params,
            if HAS_TIME_UNIT {
                self.configuration.time_unit
            } else {
                None
            },
            true,
        )
        .await
    }
}

#[cfg(all(test, feature = "vip_loan"))]
mod tests {
    use super::*;
    use crate::TOKIO_SHARED_RT;
    use crate::{errors::ConnectorError, models::DataFuture, models::RestApiRateLimit};
    use async_trait::async_trait;
    use std::collections::HashMap;

    struct DummyRestApiResponse<T> {
        inner: Box<dyn FnOnce() -> DataFuture<Result<T, ConnectorError>> + Send + Sync>,
        status: u16,
        headers: HashMap<String, String>,
        rate_limits: Option<Vec<RestApiRateLimit>>,
    }

    impl<T> From<DummyRestApiResponse<T>> for RestApiResponse<T> {
        fn from(dummy: DummyRestApiResponse<T>) -> Self {
            Self {
                data_fn: dummy.inner,
                status: dummy.status,
                headers: dummy.headers,
                rate_limits: dummy.rate_limits,
            }
        }
    }

    struct MockMarketDataApiClient {
        force_error: bool,
    }

    #[async_trait]
    impl MarketDataApi for MockMarketDataApiClient {
        async fn get_borrow_interest_rate(
            &self,
            _params: GetBorrowInterestRateParams,
        ) -> anyhow::Result<RestApiResponse<Vec<models::GetBorrowInterestRateResponseInner>>>
        {
            if self.force_error {
                return Err(ConnectorError::ConnectorClientError {
                    msg: "ResponseError".to_string(),
                    code: None,
                }
                .into());
            }

            let resp_json: Value = serde_json::from_str(r#"[{"asset":"BUSD","flexibleDailyInterestRate":"0.001503","flexibleYearlyInterestRate":"0.548595","time":1577233578000},{"asset":"BTC","flexibleDailyInterestRate":"0.001503","flexibleYearlyInterestRate":"0.548595","time":1577233562000}]"#).unwrap();
            let dummy_response: Vec<models::GetBorrowInterestRateResponseInner> =
                serde_json::from_value(resp_json.clone())
                    .expect("should parse into Vec<models::GetBorrowInterestRateResponseInner>");

            let dummy = DummyRestApiResponse {
                inner: Box::new(move || Box::pin(async move { Ok(dummy_response) })),
                status: 200,
                headers: HashMap::new(),
                rate_limits: None,
            };

            Ok(dummy.into())
        }

        async fn get_collateral_asset_data(
            &self,
            _params: GetCollateralAssetDataParams,
        ) -> anyhow::Result<RestApiResponse<models::GetCollateralAssetDataResponse>> {
            if self.force_error {
                return Err(ConnectorError::ConnectorClientError {
                    msg: "ResponseError".to_string(),
                    code: None,
                }
                .into());
            }

            let resp_json: Value = serde_json::from_str(r#"{"rows":[{"collateralCoin":"BUSD","_1stCollateralRatio":"100%","_1stCollateralRange":"1-10000000","_2ndCollateralRatio":"80%","_2ndCollateralRange":"10000000-100000000","_3rdCollateralRatio":"60%","_3rdCollateralRange":"100000000-1000000000","_4thCollateralRatio":"0%","_4thCollateralRange":">10000000000"}],"total":1}"#).unwrap();
            let dummy_response: models::GetCollateralAssetDataResponse =
                serde_json::from_value(resp_json.clone())
                    .expect("should parse into models::GetCollateralAssetDataResponse");

            let dummy = DummyRestApiResponse {
                inner: Box::new(move || Box::pin(async move { Ok(dummy_response) })),
                status: 200,
                headers: HashMap::new(),
                rate_limits: None,
            };

            Ok(dummy.into())
        }

        async fn get_loanable_assets_data(
            &self,
            _params: GetLoanableAssetsDataParams,
        ) -> anyhow::Result<RestApiResponse<models::GetLoanableAssetsDataResponse>> {
            if self.force_error {
                return Err(ConnectorError::ConnectorClientError {
                    msg: "ResponseError".to_string(),
                    code: None,
                }
                .into());
            }

            let resp_json: Value = serde_json::from_str(r#"{"rows":[{"loanCoin":"BUSD","_flexibleDailyInterestRate":"0.001503","_flexibleYearlyInterestRate":"0.548595","_30dDailyInterestRate":"0.000136","_30dYearlyInterestRate":"0.03450","_60dDailyInterestRate":"0.000145","_60dYearlyInterestRate":"0.04103","minLimit":"100","maxLimit":"1000000","vipLevel":1}],"total":1}"#).unwrap();
            let dummy_response: models::GetLoanableAssetsDataResponse =
                serde_json::from_value(resp_json.clone())
                    .expect("should parse into models::GetLoanableAssetsDataResponse");

            let dummy = DummyRestApiResponse {
                inner: Box::new(move || Box::pin(async move { Ok(dummy_response) })),
                status: 200,
                headers: HashMap::new(),
                rate_limits: None,
            };

            Ok(dummy.into())
        }

        async fn get_vip_loan_interest_rate_history(
            &self,
            _params: GetVipLoanInterestRateHistoryParams,
        ) -> anyhow::Result<RestApiResponse<models::GetVipLoanInterestRateHistoryResponse>>
        {
            if self.force_error {
                return Err(ConnectorError::ConnectorClientError {
                    msg: "ResponseError".to_string(),
                    code: None,
                }
                .into());
            }

            let resp_json: Value = serde_json::from_str(r#"{"rows":[{"coin":"USDT","annualizedInterestRate":"0.0647","time":1575018510000}],"total":1}"#).unwrap();
            let dummy_response: models::GetVipLoanInterestRateHistoryResponse =
                serde_json::from_value(resp_json.clone())
                    .expect("should parse into models::GetVipLoanInterestRateHistoryResponse");

            let dummy = DummyRestApiResponse {
                inner: Box::new(move || Box::pin(async move { Ok(dummy_response) })),
                status: 200,
                headers: HashMap::new(),
                rate_limits: None,
            };

            Ok(dummy.into())
        }
    }

    #[test]
    fn get_borrow_interest_rate_required_params_success() {
        TOKIO_SHARED_RT.block_on(async {
            let client = MockMarketDataApiClient { force_error: false };

            let params = GetBorrowInterestRateParams::builder("loan_coin_example".to_string(),).build().unwrap();

            let resp_json: Value = serde_json::from_str(r#"[{"asset":"BUSD","flexibleDailyInterestRate":"0.001503","flexibleYearlyInterestRate":"0.548595","time":1577233578000},{"asset":"BTC","flexibleDailyInterestRate":"0.001503","flexibleYearlyInterestRate":"0.548595","time":1577233562000}]"#).unwrap();
            let expected_response : Vec<models::GetBorrowInterestRateResponseInner> = serde_json::from_value(resp_json.clone()).expect("should parse into Vec<models::GetBorrowInterestRateResponseInner>");

            let resp = client.get_borrow_interest_rate(params).await.expect("Expected a response");
            let data_future = resp.data();
            let actual_response = data_future.await.unwrap();
            assert_eq!(actual_response, expected_response);
        });
    }

    #[test]
    fn get_borrow_interest_rate_optional_params_success() {
        TOKIO_SHARED_RT.block_on(async {
            let client = MockMarketDataApiClient { force_error: false };

            let params = GetBorrowInterestRateParams::builder("loan_coin_example".to_string(),).recv_window(5000).build().unwrap();

            let resp_json: Value = serde_json::from_str(r#"[{"asset":"BUSD","flexibleDailyInterestRate":"0.001503","flexibleYearlyInterestRate":"0.548595","time":1577233578000},{"asset":"BTC","flexibleDailyInterestRate":"0.001503","flexibleYearlyInterestRate":"0.548595","time":1577233562000}]"#).unwrap();
            let expected_response : Vec<models::GetBorrowInterestRateResponseInner> = serde_json::from_value(resp_json.clone()).expect("should parse into Vec<models::GetBorrowInterestRateResponseInner>");

            let resp = client.get_borrow_interest_rate(params).await.expect("Expected a response");
            let data_future = resp.data();
            let actual_response = data_future.await.unwrap();
            assert_eq!(actual_response, expected_response);
        });
    }

    #[test]
    fn get_borrow_interest_rate_response_error() {
        TOKIO_SHARED_RT.block_on(async {
            let client = MockMarketDataApiClient { force_error: true };

            let params = GetBorrowInterestRateParams::builder("loan_coin_example".to_string())
                .build()
                .unwrap();

            match client.get_borrow_interest_rate(params).await {
                Ok(_) => panic!("Expected an error"),
                Err(err) => {
                    assert_eq!(err.to_string(), "Connector client error: ResponseError");
                }
            }
        });
    }

    #[test]
    fn get_collateral_asset_data_required_params_success() {
        TOKIO_SHARED_RT.block_on(async {
            let client = MockMarketDataApiClient { force_error: false };

            let params = GetCollateralAssetDataParams::builder().build().unwrap();

            let resp_json: Value = serde_json::from_str(r#"{"rows":[{"collateralCoin":"BUSD","_1stCollateralRatio":"100%","_1stCollateralRange":"1-10000000","_2ndCollateralRatio":"80%","_2ndCollateralRange":"10000000-100000000","_3rdCollateralRatio":"60%","_3rdCollateralRange":"100000000-1000000000","_4thCollateralRatio":"0%","_4thCollateralRange":">10000000000"}],"total":1}"#).unwrap();
            let expected_response : models::GetCollateralAssetDataResponse = serde_json::from_value(resp_json.clone()).expect("should parse into models::GetCollateralAssetDataResponse");

            let resp = client.get_collateral_asset_data(params).await.expect("Expected a response");
            let data_future = resp.data();
            let actual_response = data_future.await.unwrap();
            assert_eq!(actual_response, expected_response);
        });
    }

    #[test]
    fn get_collateral_asset_data_optional_params_success() {
        TOKIO_SHARED_RT.block_on(async {
            let client = MockMarketDataApiClient { force_error: false };

            let params = GetCollateralAssetDataParams::builder().collateral_coin("collateral_coin_example".to_string()).recv_window(5000).build().unwrap();

            let resp_json: Value = serde_json::from_str(r#"{"rows":[{"collateralCoin":"BUSD","_1stCollateralRatio":"100%","_1stCollateralRange":"1-10000000","_2ndCollateralRatio":"80%","_2ndCollateralRange":"10000000-100000000","_3rdCollateralRatio":"60%","_3rdCollateralRange":"100000000-1000000000","_4thCollateralRatio":"0%","_4thCollateralRange":">10000000000"}],"total":1}"#).unwrap();
            let expected_response : models::GetCollateralAssetDataResponse = serde_json::from_value(resp_json.clone()).expect("should parse into models::GetCollateralAssetDataResponse");

            let resp = client.get_collateral_asset_data(params).await.expect("Expected a response");
            let data_future = resp.data();
            let actual_response = data_future.await.unwrap();
            assert_eq!(actual_response, expected_response);
        });
    }

    #[test]
    fn get_collateral_asset_data_response_error() {
        TOKIO_SHARED_RT.block_on(async {
            let client = MockMarketDataApiClient { force_error: true };

            let params = GetCollateralAssetDataParams::builder().build().unwrap();

            match client.get_collateral_asset_data(params).await {
                Ok(_) => panic!("Expected an error"),
                Err(err) => {
                    assert_eq!(err.to_string(), "Connector client error: ResponseError");
                }
            }
        });
    }

    #[test]
    fn get_loanable_assets_data_required_params_success() {
        TOKIO_SHARED_RT.block_on(async {
            let client = MockMarketDataApiClient { force_error: false };

            let params = GetLoanableAssetsDataParams::builder().build().unwrap();

            let resp_json: Value = serde_json::from_str(r#"{"rows":[{"loanCoin":"BUSD","_flexibleDailyInterestRate":"0.001503","_flexibleYearlyInterestRate":"0.548595","_30dDailyInterestRate":"0.000136","_30dYearlyInterestRate":"0.03450","_60dDailyInterestRate":"0.000145","_60dYearlyInterestRate":"0.04103","minLimit":"100","maxLimit":"1000000","vipLevel":1}],"total":1}"#).unwrap();
            let expected_response : models::GetLoanableAssetsDataResponse = serde_json::from_value(resp_json.clone()).expect("should parse into models::GetLoanableAssetsDataResponse");

            let resp = client.get_loanable_assets_data(params).await.expect("Expected a response");
            let data_future = resp.data();
            let actual_response = data_future.await.unwrap();
            assert_eq!(actual_response, expected_response);
        });
    }

    #[test]
    fn get_loanable_assets_data_optional_params_success() {
        TOKIO_SHARED_RT.block_on(async {
            let client = MockMarketDataApiClient { force_error: false };

            let params = GetLoanableAssetsDataParams::builder().loan_coin("loan_coin_example".to_string()).vip_level(1).recv_window(5000).build().unwrap();

            let resp_json: Value = serde_json::from_str(r#"{"rows":[{"loanCoin":"BUSD","_flexibleDailyInterestRate":"0.001503","_flexibleYearlyInterestRate":"0.548595","_30dDailyInterestRate":"0.000136","_30dYearlyInterestRate":"0.03450","_60dDailyInterestRate":"0.000145","_60dYearlyInterestRate":"0.04103","minLimit":"100","maxLimit":"1000000","vipLevel":1}],"total":1}"#).unwrap();
            let expected_response : models::GetLoanableAssetsDataResponse = serde_json::from_value(resp_json.clone()).expect("should parse into models::GetLoanableAssetsDataResponse");

            let resp = client.get_loanable_assets_data(params).await.expect("Expected a response");
            let data_future = resp.data();
            let actual_response = data_future.await.unwrap();
            assert_eq!(actual_response, expected_response);
        });
    }

    #[test]
    fn get_loanable_assets_data_response_error() {
        TOKIO_SHARED_RT.block_on(async {
            let client = MockMarketDataApiClient { force_error: true };

            let params = GetLoanableAssetsDataParams::builder().build().unwrap();

            match client.get_loanable_assets_data(params).await {
                Ok(_) => panic!("Expected an error"),
                Err(err) => {
                    assert_eq!(err.to_string(), "Connector client error: ResponseError");
                }
            }
        });
    }

    #[test]
    fn get_vip_loan_interest_rate_history_required_params_success() {
        TOKIO_SHARED_RT.block_on(async {
            let client = MockMarketDataApiClient { force_error: false };

            let params = GetVipLoanInterestRateHistoryParams::builder("coin_example".to_string(),5000,).build().unwrap();

            let resp_json: Value = serde_json::from_str(r#"{"rows":[{"coin":"USDT","annualizedInterestRate":"0.0647","time":1575018510000}],"total":1}"#).unwrap();
            let expected_response : models::GetVipLoanInterestRateHistoryResponse = serde_json::from_value(resp_json.clone()).expect("should parse into models::GetVipLoanInterestRateHistoryResponse");

            let resp = client.get_vip_loan_interest_rate_history(params).await.expect("Expected a response");
            let data_future = resp.data();
            let actual_response = data_future.await.unwrap();
            assert_eq!(actual_response, expected_response);
        });
    }

    #[test]
    fn get_vip_loan_interest_rate_history_optional_params_success() {
        TOKIO_SHARED_RT.block_on(async {
            let client = MockMarketDataApiClient { force_error: false };

            let params = GetVipLoanInterestRateHistoryParams::builder("coin_example".to_string(),5000,).start_time(1623319461670).end_time(1641782889000).current(1).limit(10).build().unwrap();

            let resp_json: Value = serde_json::from_str(r#"{"rows":[{"coin":"USDT","annualizedInterestRate":"0.0647","time":1575018510000}],"total":1}"#).unwrap();
            let expected_response : models::GetVipLoanInterestRateHistoryResponse = serde_json::from_value(resp_json.clone()).expect("should parse into models::GetVipLoanInterestRateHistoryResponse");

            let resp = client.get_vip_loan_interest_rate_history(params).await.expect("Expected a response");
            let data_future = resp.data();
            let actual_response = data_future.await.unwrap();
            assert_eq!(actual_response, expected_response);
        });
    }

    #[test]
    fn get_vip_loan_interest_rate_history_response_error() {
        TOKIO_SHARED_RT.block_on(async {
            let client = MockMarketDataApiClient { force_error: true };

            let params =
                GetVipLoanInterestRateHistoryParams::builder("coin_example".to_string(), 5000)
                    .build()
                    .unwrap();

            match client.get_vip_loan_interest_rate_history(params).await {
                Ok(_) => panic!("Expected an error"),
                Err(err) => {
                    assert_eq!(err.to_string(), "Connector client error: ResponseError");
                }
            }
        });
    }
}
