/*
 * Binance Simple Earn REST API
 *
 * OpenAPI Specification for the Binance Simple Earn 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::simple_earn::rest_api::models;

const HAS_TIME_UNIT: bool = false;

#[async_trait]
pub trait RwusdApi: Send + Sync {
    async fn get_rwusd_account(
        &self,
        params: GetRwusdAccountParams,
    ) -> anyhow::Result<RestApiResponse<models::GetRwusdAccountResponse>>;
    async fn get_rwusd_quota_details(
        &self,
        params: GetRwusdQuotaDetailsParams,
    ) -> anyhow::Result<RestApiResponse<models::GetRwusdQuotaDetailsResponse>>;
    async fn get_rwusd_rate_history(
        &self,
        params: GetRwusdRateHistoryParams,
    ) -> anyhow::Result<RestApiResponse<models::GetRwusdRateHistoryResponse>>;
    async fn get_rwusd_redemption_history(
        &self,
        params: GetRwusdRedemptionHistoryParams,
    ) -> anyhow::Result<RestApiResponse<models::GetRwusdRedemptionHistoryResponse>>;
    async fn get_rwusd_rewards_history(
        &self,
        params: GetRwusdRewardsHistoryParams,
    ) -> anyhow::Result<RestApiResponse<models::GetRwusdRewardsHistoryResponse>>;
    async fn get_rwusd_subscription_history(
        &self,
        params: GetRwusdSubscriptionHistoryParams,
    ) -> anyhow::Result<RestApiResponse<models::GetRwusdSubscriptionHistoryResponse>>;
    async fn redeem_rwusd(
        &self,
        params: RedeemRwusdParams,
    ) -> anyhow::Result<RestApiResponse<models::RedeemRwusdResponse>>;
    async fn subscribe_rwusd(
        &self,
        params: SubscribeRwusdParams,
    ) -> anyhow::Result<RestApiResponse<models::SubscribeRwusdResponse>>;
}

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

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

/// Request parameters for the [`get_rwusd_account`] operation.
///
/// This struct holds all of the inputs you can pass when calling
/// [`get_rwusd_account`](#method.get_rwusd_account).
#[derive(Clone, Debug, Builder, Default)]
#[builder(pattern = "owned", build_fn(error = "ParamBuildError"))]
pub struct GetRwusdAccountParams {
    /// The value cannot be greater than 60000 (ms)
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub recv_window: Option<i64>,
}

impl GetRwusdAccountParams {
    /// Create a builder for [`get_rwusd_account`].
    ///
    #[must_use]
    pub fn builder() -> GetRwusdAccountParamsBuilder {
        GetRwusdAccountParamsBuilder::default()
    }
}
/// Request parameters for the [`get_rwusd_quota_details`] operation.
///
/// This struct holds all of the inputs you can pass when calling
/// [`get_rwusd_quota_details`](#method.get_rwusd_quota_details).
#[derive(Clone, Debug, Builder, Default)]
#[builder(pattern = "owned", build_fn(error = "ParamBuildError"))]
pub struct GetRwusdQuotaDetailsParams {
    /// The value cannot be greater than 60000 (ms)
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub recv_window: Option<i64>,
}

impl GetRwusdQuotaDetailsParams {
    /// Create a builder for [`get_rwusd_quota_details`].
    ///
    #[must_use]
    pub fn builder() -> GetRwusdQuotaDetailsParamsBuilder {
        GetRwusdQuotaDetailsParamsBuilder::default()
    }
}
/// Request parameters for the [`get_rwusd_rate_history`] operation.
///
/// This struct holds all of the inputs you can pass when calling
/// [`get_rwusd_rate_history`](#method.get_rwusd_rate_history).
#[derive(Clone, Debug, Builder, Default)]
#[builder(pattern = "owned", build_fn(error = "ParamBuildError"))]
pub struct GetRwusdRateHistoryParams {
    ///
    /// 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>,
    /// Currently querying page. Starts from 1. Default: 1
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub current: Option<i64>,
    /// Number of results per page. Default: 10, Max: 100
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub size: Option<i64>,
    /// The value cannot be greater than 60000 (ms)
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub recv_window: Option<i64>,
}

impl GetRwusdRateHistoryParams {
    /// Create a builder for [`get_rwusd_rate_history`].
    ///
    #[must_use]
    pub fn builder() -> GetRwusdRateHistoryParamsBuilder {
        GetRwusdRateHistoryParamsBuilder::default()
    }
}
/// Request parameters for the [`get_rwusd_redemption_history`] operation.
///
/// This struct holds all of the inputs you can pass when calling
/// [`get_rwusd_redemption_history`](#method.get_rwusd_redemption_history).
#[derive(Clone, Debug, Builder, Default)]
#[builder(pattern = "owned", build_fn(error = "ParamBuildError"))]
pub struct GetRwusdRedemptionHistoryParams {
    ///
    /// 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>,
    /// Currently querying page. Starts from 1. Default: 1
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub current: Option<i64>,
    /// Number of results per page. Default: 10, Max: 100
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub size: Option<i64>,
    /// The value cannot be greater than 60000 (ms)
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub recv_window: Option<i64>,
}

impl GetRwusdRedemptionHistoryParams {
    /// Create a builder for [`get_rwusd_redemption_history`].
    ///
    #[must_use]
    pub fn builder() -> GetRwusdRedemptionHistoryParamsBuilder {
        GetRwusdRedemptionHistoryParamsBuilder::default()
    }
}
/// Request parameters for the [`get_rwusd_rewards_history`] operation.
///
/// This struct holds all of the inputs you can pass when calling
/// [`get_rwusd_rewards_history`](#method.get_rwusd_rewards_history).
#[derive(Clone, Debug, Builder, Default)]
#[builder(pattern = "owned", build_fn(error = "ParamBuildError"))]
pub struct GetRwusdRewardsHistoryParams {
    ///
    /// 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>,
    /// Currently querying page. Starts from 1. Default: 1
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub current: Option<i64>,
    /// Number of results per page. Default: 10, Max: 100
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub size: Option<i64>,
    /// The value cannot be greater than 60000 (ms)
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub recv_window: Option<i64>,
}

impl GetRwusdRewardsHistoryParams {
    /// Create a builder for [`get_rwusd_rewards_history`].
    ///
    #[must_use]
    pub fn builder() -> GetRwusdRewardsHistoryParamsBuilder {
        GetRwusdRewardsHistoryParamsBuilder::default()
    }
}
/// Request parameters for the [`get_rwusd_subscription_history`] operation.
///
/// This struct holds all of the inputs you can pass when calling
/// [`get_rwusd_subscription_history`](#method.get_rwusd_subscription_history).
#[derive(Clone, Debug, Builder, Default)]
#[builder(pattern = "owned", build_fn(error = "ParamBuildError"))]
pub struct GetRwusdSubscriptionHistoryParams {
    /// USDC or USDT
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub asset: Option<String>,
    ///
    /// 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>,
    /// Currently querying page. Starts from 1. Default: 1
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub current: Option<i64>,
    /// Number of results per page. Default: 10, Max: 100
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub size: Option<i64>,
    /// The value cannot be greater than 60000 (ms)
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub recv_window: Option<i64>,
}

impl GetRwusdSubscriptionHistoryParams {
    /// Create a builder for [`get_rwusd_subscription_history`].
    ///
    #[must_use]
    pub fn builder() -> GetRwusdSubscriptionHistoryParamsBuilder {
        GetRwusdSubscriptionHistoryParamsBuilder::default()
    }
}
/// Request parameters for the [`redeem_rwusd`] operation.
///
/// This struct holds all of the inputs you can pass when calling
/// [`redeem_rwusd`](#method.redeem_rwusd).
#[derive(Clone, Debug, Builder)]
#[builder(pattern = "owned", build_fn(error = "ParamBuildError"))]
pub struct RedeemRwusdParams {
    /// Amount
    ///
    /// This field is **required.
    #[builder(setter(into))]
    pub amount: rust_decimal::Decimal,
    /// FAST or STANDARD, defaults to STANDARD
    ///
    /// This field is **required.
    #[builder(setter(into))]
    pub r#type: String,
    /// The value cannot be greater than 60000 (ms)
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub recv_window: Option<i64>,
}

impl RedeemRwusdParams {
    /// Create a builder for [`redeem_rwusd`].
    ///
    /// Required parameters:
    ///
    /// * `amount` — Amount
    /// * `r#type` — FAST or STANDARD, defaults to STANDARD
    ///
    #[must_use]
    pub fn builder(amount: rust_decimal::Decimal, r#type: String) -> RedeemRwusdParamsBuilder {
        RedeemRwusdParamsBuilder::default()
            .amount(amount)
            .r#type(r#type)
    }
}
/// Request parameters for the [`subscribe_rwusd`] operation.
///
/// This struct holds all of the inputs you can pass when calling
/// [`subscribe_rwusd`](#method.subscribe_rwusd).
#[derive(Clone, Debug, Builder)]
#[builder(pattern = "owned", build_fn(error = "ParamBuildError"))]
pub struct SubscribeRwusdParams {
    /// USDT or USDC (whichever is eligible)
    ///
    /// This field is **required.
    #[builder(setter(into))]
    pub asset: String,
    /// Amount
    ///
    /// This field is **required.
    #[builder(setter(into))]
    pub amount: rust_decimal::Decimal,
    /// The value cannot be greater than 60000 (ms)
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub recv_window: Option<i64>,
}

impl SubscribeRwusdParams {
    /// Create a builder for [`subscribe_rwusd`].
    ///
    /// Required parameters:
    ///
    /// * `asset` — USDT or USDC (whichever is eligible)
    /// * `amount` — Amount
    ///
    #[must_use]
    pub fn builder(asset: String, amount: rust_decimal::Decimal) -> SubscribeRwusdParamsBuilder {
        SubscribeRwusdParamsBuilder::default()
            .asset(asset)
            .amount(amount)
    }
}

#[async_trait]
impl RwusdApi for RwusdApiClient {
    async fn get_rwusd_account(
        &self,
        params: GetRwusdAccountParams,
    ) -> anyhow::Result<RestApiResponse<models::GetRwusdAccountResponse>> {
        let GetRwusdAccountParams { recv_window } = params;

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

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

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

    async fn get_rwusd_quota_details(
        &self,
        params: GetRwusdQuotaDetailsParams,
    ) -> anyhow::Result<RestApiResponse<models::GetRwusdQuotaDetailsResponse>> {
        let GetRwusdQuotaDetailsParams { recv_window } = params;

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

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

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

    async fn get_rwusd_rate_history(
        &self,
        params: GetRwusdRateHistoryParams,
    ) -> anyhow::Result<RestApiResponse<models::GetRwusdRateHistoryResponse>> {
        let GetRwusdRateHistoryParams {
            start_time,
            end_time,
            current,
            size,
            recv_window,
        } = params;

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

        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) = size {
            query_params.insert("size".to_string(), json!(rw));
        }

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

        send_request::<models::GetRwusdRateHistoryResponse>(
            &self.configuration,
            "/sapi/v1/rwusd/history/rateHistory",
            reqwest::Method::GET,
            query_params,
            body_params,
            if HAS_TIME_UNIT {
                self.configuration.time_unit
            } else {
                None
            },
            true,
        )
        .await
    }

    async fn get_rwusd_redemption_history(
        &self,
        params: GetRwusdRedemptionHistoryParams,
    ) -> anyhow::Result<RestApiResponse<models::GetRwusdRedemptionHistoryResponse>> {
        let GetRwusdRedemptionHistoryParams {
            start_time,
            end_time,
            current,
            size,
            recv_window,
        } = params;

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

        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) = size {
            query_params.insert("size".to_string(), json!(rw));
        }

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

        send_request::<models::GetRwusdRedemptionHistoryResponse>(
            &self.configuration,
            "/sapi/v1/rwusd/history/redemptionHistory",
            reqwest::Method::GET,
            query_params,
            body_params,
            if HAS_TIME_UNIT {
                self.configuration.time_unit
            } else {
                None
            },
            true,
        )
        .await
    }

    async fn get_rwusd_rewards_history(
        &self,
        params: GetRwusdRewardsHistoryParams,
    ) -> anyhow::Result<RestApiResponse<models::GetRwusdRewardsHistoryResponse>> {
        let GetRwusdRewardsHistoryParams {
            start_time,
            end_time,
            current,
            size,
            recv_window,
        } = params;

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

        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) = size {
            query_params.insert("size".to_string(), json!(rw));
        }

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

        send_request::<models::GetRwusdRewardsHistoryResponse>(
            &self.configuration,
            "/sapi/v1/rwusd/history/rewardsHistory",
            reqwest::Method::GET,
            query_params,
            body_params,
            if HAS_TIME_UNIT {
                self.configuration.time_unit
            } else {
                None
            },
            true,
        )
        .await
    }

    async fn get_rwusd_subscription_history(
        &self,
        params: GetRwusdSubscriptionHistoryParams,
    ) -> anyhow::Result<RestApiResponse<models::GetRwusdSubscriptionHistoryResponse>> {
        let GetRwusdSubscriptionHistoryParams {
            asset,
            start_time,
            end_time,
            current,
            size,
            recv_window,
        } = params;

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

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

        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) = size {
            query_params.insert("size".to_string(), json!(rw));
        }

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

        send_request::<models::GetRwusdSubscriptionHistoryResponse>(
            &self.configuration,
            "/sapi/v1/rwusd/history/subscriptionHistory",
            reqwest::Method::GET,
            query_params,
            body_params,
            if HAS_TIME_UNIT {
                self.configuration.time_unit
            } else {
                None
            },
            true,
        )
        .await
    }

    async fn redeem_rwusd(
        &self,
        params: RedeemRwusdParams,
    ) -> anyhow::Result<RestApiResponse<models::RedeemRwusdResponse>> {
        let RedeemRwusdParams {
            amount,
            r#type,
            recv_window,
        } = params;

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

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

        query_params.insert("type".to_string(), json!(r#type));

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

        send_request::<models::RedeemRwusdResponse>(
            &self.configuration,
            "/sapi/v1/rwusd/redeem",
            reqwest::Method::POST,
            query_params,
            body_params,
            if HAS_TIME_UNIT {
                self.configuration.time_unit
            } else {
                None
            },
            true,
        )
        .await
    }

    async fn subscribe_rwusd(
        &self,
        params: SubscribeRwusdParams,
    ) -> anyhow::Result<RestApiResponse<models::SubscribeRwusdResponse>> {
        let SubscribeRwusdParams {
            asset,
            amount,
            recv_window,
        } = params;

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

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

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

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

        send_request::<models::SubscribeRwusdResponse>(
            &self.configuration,
            "/sapi/v1/rwusd/subscribe",
            reqwest::Method::POST,
            query_params,
            body_params,
            if HAS_TIME_UNIT {
                self.configuration.time_unit
            } else {
                None
            },
            true,
        )
        .await
    }
}

#[cfg(all(test, feature = "simple_earn"))]
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 MockRwusdApiClient {
        force_error: bool,
    }

    #[async_trait]
    impl RwusdApi for MockRwusdApiClient {
        async fn get_rwusd_account(
            &self,
            _params: GetRwusdAccountParams,
        ) -> anyhow::Result<RestApiResponse<models::GetRwusdAccountResponse>> {
            if self.force_error {
                return Err(ConnectorError::ConnectorClientError {
                    msg: "ResponseError".to_string(),
                    code: None,
                }
                .into());
            }

            let resp_json: Value =
                serde_json::from_str(r#"{"rwusdAmount":"100","totalProfit":"12.81"}"#).unwrap();
            let dummy_response: models::GetRwusdAccountResponse =
                serde_json::from_value(resp_json.clone())
                    .expect("should parse into models::GetRwusdAccountResponse");

            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_rwusd_quota_details(
            &self,
            _params: GetRwusdQuotaDetailsParams,
        ) -> anyhow::Result<RestApiResponse<models::GetRwusdQuotaDetailsResponse>> {
            if self.force_error {
                return Err(ConnectorError::ConnectorClientError {
                    msg: "ResponseError".to_string(),
                    code: None,
                }
                .into());
            }

            let resp_json: Value = serde_json::from_str(r#"{"subscriptionQuota":{"assets":["USDT","USDC"],"leftQuota":"1000","minimum":"0.10000000"},"fastRedemptionQuota":{"leftQuota":"2","minimum":"0.1","fee":"0.0005","freeQuota":"100"},"standardRedemptionQuota":{"leftQuota":"2","minimum":"0.1","fee":"0.001","redeemPeriod":3},"subscribeEnable":true,"redeemEnable":true}"#).unwrap();
            let dummy_response: models::GetRwusdQuotaDetailsResponse =
                serde_json::from_value(resp_json.clone())
                    .expect("should parse into models::GetRwusdQuotaDetailsResponse");

            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_rwusd_rate_history(
            &self,
            _params: GetRwusdRateHistoryParams,
        ) -> anyhow::Result<RestApiResponse<models::GetRwusdRateHistoryResponse>> {
            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":[{"annualPercentageRate":"0.0418","time":1577233578000}],"total":"1"}"#,
            )
            .unwrap();
            let dummy_response: models::GetRwusdRateHistoryResponse =
                serde_json::from_value(resp_json.clone())
                    .expect("should parse into models::GetRwusdRateHistoryResponse");

            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_rwusd_redemption_history(
            &self,
            _params: GetRwusdRedemptionHistoryParams,
        ) -> anyhow::Result<RestApiResponse<models::GetRwusdRedemptionHistoryResponse>> {
            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":[{"time":1575018510000,"asset":"RWUSD","amount":"51","receiveAsset":"USDC","receiveAmount":"50","fee":"1","arrivalTime":1575018510000,"status":"SUCCESS"}],"total":1}"#).unwrap();
            let dummy_response: models::GetRwusdRedemptionHistoryResponse =
                serde_json::from_value(resp_json.clone())
                    .expect("should parse into models::GetRwusdRedemptionHistoryResponse");

            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_rwusd_rewards_history(
            &self,
            _params: GetRwusdRewardsHistoryParams,
        ) -> anyhow::Result<RestApiResponse<models::GetRwusdRewardsHistoryResponse>> {
            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":[{"time":1575018510000,"rewardsAmount":"1","rwusdPosition":"100","annualPercentageRate":"0.0418"}],"total":1}"#).unwrap();
            let dummy_response: models::GetRwusdRewardsHistoryResponse =
                serde_json::from_value(resp_json.clone())
                    .expect("should parse into models::GetRwusdRewardsHistoryResponse");

            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_rwusd_subscription_history(
            &self,
            _params: GetRwusdSubscriptionHistoryParams,
        ) -> anyhow::Result<RestApiResponse<models::GetRwusdSubscriptionHistoryResponse>> {
            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":[{"time":1575018510000,"asset":"USDC","amount":"100","receiveAsset":"RWUSD","receiveAmount":"100","status":"SUCCESS"}],"total":1}"#).unwrap();
            let dummy_response: models::GetRwusdSubscriptionHistoryResponse =
                serde_json::from_value(resp_json.clone())
                    .expect("should parse into models::GetRwusdSubscriptionHistoryResponse");

            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 redeem_rwusd(
            &self,
            _params: RedeemRwusdParams,
        ) -> anyhow::Result<RestApiResponse<models::RedeemRwusdResponse>> {
            if self.force_error {
                return Err(ConnectorError::ConnectorClientError {
                    msg: "ResponseError".to_string(),
                    code: None,
                }
                .into());
            }

            let resp_json: Value = serde_json::from_str(r#"{"success":true,"receiveAmount":"0.23092091","fee":"0.00000012","arrivalTime":1575018510000}"#).unwrap();
            let dummy_response: models::RedeemRwusdResponse =
                serde_json::from_value(resp_json.clone())
                    .expect("should parse into models::RedeemRwusdResponse");

            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 subscribe_rwusd(
            &self,
            _params: SubscribeRwusdParams,
        ) -> anyhow::Result<RestApiResponse<models::SubscribeRwusdResponse>> {
            if self.force_error {
                return Err(ConnectorError::ConnectorClientError {
                    msg: "ResponseError".to_string(),
                    code: None,
                }
                .into());
            }

            let resp_json: Value =
                serde_json::from_str(r#"{"success":true,"rwusdAmount":"0.22091092"}"#).unwrap();
            let dummy_response: models::SubscribeRwusdResponse =
                serde_json::from_value(resp_json.clone())
                    .expect("should parse into models::SubscribeRwusdResponse");

            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_rwusd_account_required_params_success() {
        TOKIO_SHARED_RT.block_on(async {
            let client = MockRwusdApiClient { force_error: false };

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

            let resp_json: Value =
                serde_json::from_str(r#"{"rwusdAmount":"100","totalProfit":"12.81"}"#).unwrap();
            let expected_response: models::GetRwusdAccountResponse =
                serde_json::from_value(resp_json.clone())
                    .expect("should parse into models::GetRwusdAccountResponse");

            let resp = client
                .get_rwusd_account(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_rwusd_account_optional_params_success() {
        TOKIO_SHARED_RT.block_on(async {
            let client = MockRwusdApiClient { force_error: false };

            let params = GetRwusdAccountParams::builder()
                .recv_window(5000)
                .build()
                .unwrap();

            let resp_json: Value =
                serde_json::from_str(r#"{"rwusdAmount":"100","totalProfit":"12.81"}"#).unwrap();
            let expected_response: models::GetRwusdAccountResponse =
                serde_json::from_value(resp_json.clone())
                    .expect("should parse into models::GetRwusdAccountResponse");

            let resp = client
                .get_rwusd_account(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_rwusd_account_response_error() {
        TOKIO_SHARED_RT.block_on(async {
            let client = MockRwusdApiClient { force_error: true };

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

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

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

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

            let resp_json: Value = serde_json::from_str(r#"{"subscriptionQuota":{"assets":["USDT","USDC"],"leftQuota":"1000","minimum":"0.10000000"},"fastRedemptionQuota":{"leftQuota":"2","minimum":"0.1","fee":"0.0005","freeQuota":"100"},"standardRedemptionQuota":{"leftQuota":"2","minimum":"0.1","fee":"0.001","redeemPeriod":3},"subscribeEnable":true,"redeemEnable":true}"#).unwrap();
            let expected_response : models::GetRwusdQuotaDetailsResponse = serde_json::from_value(resp_json.clone()).expect("should parse into models::GetRwusdQuotaDetailsResponse");

            let resp = client.get_rwusd_quota_details(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_rwusd_quota_details_optional_params_success() {
        TOKIO_SHARED_RT.block_on(async {
            let client = MockRwusdApiClient { force_error: false };

            let params = GetRwusdQuotaDetailsParams::builder().recv_window(5000).build().unwrap();

            let resp_json: Value = serde_json::from_str(r#"{"subscriptionQuota":{"assets":["USDT","USDC"],"leftQuota":"1000","minimum":"0.10000000"},"fastRedemptionQuota":{"leftQuota":"2","minimum":"0.1","fee":"0.0005","freeQuota":"100"},"standardRedemptionQuota":{"leftQuota":"2","minimum":"0.1","fee":"0.001","redeemPeriod":3},"subscribeEnable":true,"redeemEnable":true}"#).unwrap();
            let expected_response : models::GetRwusdQuotaDetailsResponse = serde_json::from_value(resp_json.clone()).expect("should parse into models::GetRwusdQuotaDetailsResponse");

            let resp = client.get_rwusd_quota_details(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_rwusd_quota_details_response_error() {
        TOKIO_SHARED_RT.block_on(async {
            let client = MockRwusdApiClient { force_error: true };

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

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

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

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

            let resp_json: Value = serde_json::from_str(
                r#"{"rows":[{"annualPercentageRate":"0.0418","time":1577233578000}],"total":"1"}"#,
            )
            .unwrap();
            let expected_response: models::GetRwusdRateHistoryResponse =
                serde_json::from_value(resp_json.clone())
                    .expect("should parse into models::GetRwusdRateHistoryResponse");

            let resp = client
                .get_rwusd_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_rwusd_rate_history_optional_params_success() {
        TOKIO_SHARED_RT.block_on(async {
            let client = MockRwusdApiClient { force_error: false };

            let params = GetRwusdRateHistoryParams::builder()
                .start_time(1623319461670)
                .end_time(1641782889000)
                .current(1)
                .size(10)
                .recv_window(5000)
                .build()
                .unwrap();

            let resp_json: Value = serde_json::from_str(
                r#"{"rows":[{"annualPercentageRate":"0.0418","time":1577233578000}],"total":"1"}"#,
            )
            .unwrap();
            let expected_response: models::GetRwusdRateHistoryResponse =
                serde_json::from_value(resp_json.clone())
                    .expect("should parse into models::GetRwusdRateHistoryResponse");

            let resp = client
                .get_rwusd_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_rwusd_rate_history_response_error() {
        TOKIO_SHARED_RT.block_on(async {
            let client = MockRwusdApiClient { force_error: true };

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

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

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

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

            let resp_json: Value = serde_json::from_str(r#"{"rows":[{"time":1575018510000,"asset":"RWUSD","amount":"51","receiveAsset":"USDC","receiveAmount":"50","fee":"1","arrivalTime":1575018510000,"status":"SUCCESS"}],"total":1}"#).unwrap();
            let expected_response : models::GetRwusdRedemptionHistoryResponse = serde_json::from_value(resp_json.clone()).expect("should parse into models::GetRwusdRedemptionHistoryResponse");

            let resp = client.get_rwusd_redemption_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_rwusd_redemption_history_optional_params_success() {
        TOKIO_SHARED_RT.block_on(async {
            let client = MockRwusdApiClient { force_error: false };

            let params = GetRwusdRedemptionHistoryParams::builder().start_time(1623319461670).end_time(1641782889000).current(1).size(10).recv_window(5000).build().unwrap();

            let resp_json: Value = serde_json::from_str(r#"{"rows":[{"time":1575018510000,"asset":"RWUSD","amount":"51","receiveAsset":"USDC","receiveAmount":"50","fee":"1","arrivalTime":1575018510000,"status":"SUCCESS"}],"total":1}"#).unwrap();
            let expected_response : models::GetRwusdRedemptionHistoryResponse = serde_json::from_value(resp_json.clone()).expect("should parse into models::GetRwusdRedemptionHistoryResponse");

            let resp = client.get_rwusd_redemption_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_rwusd_redemption_history_response_error() {
        TOKIO_SHARED_RT.block_on(async {
            let client = MockRwusdApiClient { force_error: true };

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

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

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

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

            let resp_json: Value = serde_json::from_str(r#"{"rows":[{"time":1575018510000,"rewardsAmount":"1","rwusdPosition":"100","annualPercentageRate":"0.0418"}],"total":1}"#).unwrap();
            let expected_response : models::GetRwusdRewardsHistoryResponse = serde_json::from_value(resp_json.clone()).expect("should parse into models::GetRwusdRewardsHistoryResponse");

            let resp = client.get_rwusd_rewards_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_rwusd_rewards_history_optional_params_success() {
        TOKIO_SHARED_RT.block_on(async {
            let client = MockRwusdApiClient { force_error: false };

            let params = GetRwusdRewardsHistoryParams::builder().start_time(1623319461670).end_time(1641782889000).current(1).size(10).recv_window(5000).build().unwrap();

            let resp_json: Value = serde_json::from_str(r#"{"rows":[{"time":1575018510000,"rewardsAmount":"1","rwusdPosition":"100","annualPercentageRate":"0.0418"}],"total":1}"#).unwrap();
            let expected_response : models::GetRwusdRewardsHistoryResponse = serde_json::from_value(resp_json.clone()).expect("should parse into models::GetRwusdRewardsHistoryResponse");

            let resp = client.get_rwusd_rewards_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_rwusd_rewards_history_response_error() {
        TOKIO_SHARED_RT.block_on(async {
            let client = MockRwusdApiClient { force_error: true };

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

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

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

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

            let resp_json: Value = serde_json::from_str(r#"{"rows":[{"time":1575018510000,"asset":"USDC","amount":"100","receiveAsset":"RWUSD","receiveAmount":"100","status":"SUCCESS"}],"total":1}"#).unwrap();
            let expected_response : models::GetRwusdSubscriptionHistoryResponse = serde_json::from_value(resp_json.clone()).expect("should parse into models::GetRwusdSubscriptionHistoryResponse");

            let resp = client.get_rwusd_subscription_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_rwusd_subscription_history_optional_params_success() {
        TOKIO_SHARED_RT.block_on(async {
            let client = MockRwusdApiClient { force_error: false };

            let params = GetRwusdSubscriptionHistoryParams::builder().asset("asset_example".to_string()).start_time(1623319461670).end_time(1641782889000).current(1).size(10).recv_window(5000).build().unwrap();

            let resp_json: Value = serde_json::from_str(r#"{"rows":[{"time":1575018510000,"asset":"USDC","amount":"100","receiveAsset":"RWUSD","receiveAmount":"100","status":"SUCCESS"}],"total":1}"#).unwrap();
            let expected_response : models::GetRwusdSubscriptionHistoryResponse = serde_json::from_value(resp_json.clone()).expect("should parse into models::GetRwusdSubscriptionHistoryResponse");

            let resp = client.get_rwusd_subscription_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_rwusd_subscription_history_response_error() {
        TOKIO_SHARED_RT.block_on(async {
            let client = MockRwusdApiClient { force_error: true };

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

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

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

            let params = RedeemRwusdParams::builder(dec!(1.0),"s".to_string(),).build().unwrap();

            let resp_json: Value = serde_json::from_str(r#"{"success":true,"receiveAmount":"0.23092091","fee":"0.00000012","arrivalTime":1575018510000}"#).unwrap();
            let expected_response : models::RedeemRwusdResponse = serde_json::from_value(resp_json.clone()).expect("should parse into models::RedeemRwusdResponse");

            let resp = client.redeem_rwusd(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 redeem_rwusd_optional_params_success() {
        TOKIO_SHARED_RT.block_on(async {
            let client = MockRwusdApiClient { force_error: false };

            let params = RedeemRwusdParams::builder(dec!(1.0),"s".to_string(),).recv_window(5000).build().unwrap();

            let resp_json: Value = serde_json::from_str(r#"{"success":true,"receiveAmount":"0.23092091","fee":"0.00000012","arrivalTime":1575018510000}"#).unwrap();
            let expected_response : models::RedeemRwusdResponse = serde_json::from_value(resp_json.clone()).expect("should parse into models::RedeemRwusdResponse");

            let resp = client.redeem_rwusd(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 redeem_rwusd_response_error() {
        TOKIO_SHARED_RT.block_on(async {
            let client = MockRwusdApiClient { force_error: true };

            let params = RedeemRwusdParams::builder(dec!(1.0), "s".to_string())
                .build()
                .unwrap();

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

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

            let params = SubscribeRwusdParams::builder("asset_example".to_string(), dec!(1.0))
                .build()
                .unwrap();

            let resp_json: Value =
                serde_json::from_str(r#"{"success":true,"rwusdAmount":"0.22091092"}"#).unwrap();
            let expected_response: models::SubscribeRwusdResponse =
                serde_json::from_value(resp_json.clone())
                    .expect("should parse into models::SubscribeRwusdResponse");

            let resp = client
                .subscribe_rwusd(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 subscribe_rwusd_optional_params_success() {
        TOKIO_SHARED_RT.block_on(async {
            let client = MockRwusdApiClient { force_error: false };

            let params = SubscribeRwusdParams::builder("asset_example".to_string(), dec!(1.0))
                .recv_window(5000)
                .build()
                .unwrap();

            let resp_json: Value =
                serde_json::from_str(r#"{"success":true,"rwusdAmount":"0.22091092"}"#).unwrap();
            let expected_response: models::SubscribeRwusdResponse =
                serde_json::from_value(resp_json.clone())
                    .expect("should parse into models::SubscribeRwusdResponse");

            let resp = client
                .subscribe_rwusd(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 subscribe_rwusd_response_error() {
        TOKIO_SHARED_RT.block_on(async {
            let client = MockRwusdApiClient { force_error: true };

            let params = SubscribeRwusdParams::builder("asset_example".to_string(), dec!(1.0))
                .build()
                .unwrap();

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