/*
 * 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 BfusdApi: Send + Sync {
    async fn get_bfusd_account(
        &self,
        params: GetBfusdAccountParams,
    ) -> anyhow::Result<RestApiResponse<models::GetBfusdAccountResponse>>;
    async fn get_bfusd_quota_details(
        &self,
        params: GetBfusdQuotaDetailsParams,
    ) -> anyhow::Result<RestApiResponse<models::GetBfusdQuotaDetailsResponse>>;
    async fn get_bfusd_rate_history(
        &self,
        params: GetBfusdRateHistoryParams,
    ) -> anyhow::Result<RestApiResponse<models::GetBfusdRateHistoryResponse>>;
    async fn get_bfusd_redemption_history(
        &self,
        params: GetBfusdRedemptionHistoryParams,
    ) -> anyhow::Result<RestApiResponse<models::GetBfusdRedemptionHistoryResponse>>;
    async fn get_bfusd_rewards_history(
        &self,
        params: GetBfusdRewardsHistoryParams,
    ) -> anyhow::Result<RestApiResponse<models::GetBfusdRewardsHistoryResponse>>;
    async fn get_bfusd_subscription_history(
        &self,
        params: GetBfusdSubscriptionHistoryParams,
    ) -> anyhow::Result<RestApiResponse<models::GetBfusdSubscriptionHistoryResponse>>;
    async fn redeem_bfusd(
        &self,
        params: RedeemBfusdParams,
    ) -> anyhow::Result<RestApiResponse<models::RedeemBfusdResponse>>;
    async fn subscribe_bfusd(
        &self,
        params: SubscribeBfusdParams,
    ) -> anyhow::Result<RestApiResponse<models::SubscribeBfusdResponse>>;
}

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

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

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

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

impl GetBfusdQuotaDetailsParams {
    /// Create a builder for [`get_bfusd_quota_details`].
    ///
    #[must_use]
    pub fn builder() -> GetBfusdQuotaDetailsParamsBuilder {
        GetBfusdQuotaDetailsParamsBuilder::default()
    }
}
/// Request parameters for the [`get_bfusd_rate_history`] operation.
///
/// This struct holds all of the inputs you can pass when calling
/// [`get_bfusd_rate_history`](#method.get_bfusd_rate_history).
#[derive(Clone, Debug, Builder, Default)]
#[builder(pattern = "owned", build_fn(error = "ParamBuildError"))]
pub struct GetBfusdRateHistoryParams {
    ///
    /// 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 GetBfusdRateHistoryParams {
    /// Create a builder for [`get_bfusd_rate_history`].
    ///
    #[must_use]
    pub fn builder() -> GetBfusdRateHistoryParamsBuilder {
        GetBfusdRateHistoryParamsBuilder::default()
    }
}
/// Request parameters for the [`get_bfusd_redemption_history`] operation.
///
/// This struct holds all of the inputs you can pass when calling
/// [`get_bfusd_redemption_history`](#method.get_bfusd_redemption_history).
#[derive(Clone, Debug, Builder, Default)]
#[builder(pattern = "owned", build_fn(error = "ParamBuildError"))]
pub struct GetBfusdRedemptionHistoryParams {
    ///
    /// 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 GetBfusdRedemptionHistoryParams {
    /// Create a builder for [`get_bfusd_redemption_history`].
    ///
    #[must_use]
    pub fn builder() -> GetBfusdRedemptionHistoryParamsBuilder {
        GetBfusdRedemptionHistoryParamsBuilder::default()
    }
}
/// Request parameters for the [`get_bfusd_rewards_history`] operation.
///
/// This struct holds all of the inputs you can pass when calling
/// [`get_bfusd_rewards_history`](#method.get_bfusd_rewards_history).
#[derive(Clone, Debug, Builder, Default)]
#[builder(pattern = "owned", build_fn(error = "ParamBuildError"))]
pub struct GetBfusdRewardsHistoryParams {
    ///
    /// 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 GetBfusdRewardsHistoryParams {
    /// Create a builder for [`get_bfusd_rewards_history`].
    ///
    #[must_use]
    pub fn builder() -> GetBfusdRewardsHistoryParamsBuilder {
        GetBfusdRewardsHistoryParamsBuilder::default()
    }
}
/// Request parameters for the [`get_bfusd_subscription_history`] operation.
///
/// This struct holds all of the inputs you can pass when calling
/// [`get_bfusd_subscription_history`](#method.get_bfusd_subscription_history).
#[derive(Clone, Debug, Builder, Default)]
#[builder(pattern = "owned", build_fn(error = "ParamBuildError"))]
pub struct GetBfusdSubscriptionHistoryParams {
    /// 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 GetBfusdSubscriptionHistoryParams {
    /// Create a builder for [`get_bfusd_subscription_history`].
    ///
    #[must_use]
    pub fn builder() -> GetBfusdSubscriptionHistoryParamsBuilder {
        GetBfusdSubscriptionHistoryParamsBuilder::default()
    }
}
/// Request parameters for the [`redeem_bfusd`] operation.
///
/// This struct holds all of the inputs you can pass when calling
/// [`redeem_bfusd`](#method.redeem_bfusd).
#[derive(Clone, Debug, Builder)]
#[builder(pattern = "owned", build_fn(error = "ParamBuildError"))]
pub struct RedeemBfusdParams {
    /// 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 RedeemBfusdParams {
    /// Create a builder for [`redeem_bfusd`].
    ///
    /// Required parameters:
    ///
    /// * `amount` — Amount
    /// * `r#type` — FAST or STANDARD, defaults to STANDARD
    ///
    #[must_use]
    pub fn builder(amount: rust_decimal::Decimal, r#type: String) -> RedeemBfusdParamsBuilder {
        RedeemBfusdParamsBuilder::default()
            .amount(amount)
            .r#type(r#type)
    }
}
/// Request parameters for the [`subscribe_bfusd`] operation.
///
/// This struct holds all of the inputs you can pass when calling
/// [`subscribe_bfusd`](#method.subscribe_bfusd).
#[derive(Clone, Debug, Builder)]
#[builder(pattern = "owned", build_fn(error = "ParamBuildError"))]
pub struct SubscribeBfusdParams {
    /// 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 SubscribeBfusdParams {
    /// Create a builder for [`subscribe_bfusd`].
    ///
    /// Required parameters:
    ///
    /// * `asset` — USDT or USDC (whichever is eligible)
    /// * `amount` — Amount
    ///
    #[must_use]
    pub fn builder(asset: String, amount: rust_decimal::Decimal) -> SubscribeBfusdParamsBuilder {
        SubscribeBfusdParamsBuilder::default()
            .asset(asset)
            .amount(amount)
    }
}

#[async_trait]
impl BfusdApi for BfusdApiClient {
    async fn get_bfusd_account(
        &self,
        params: GetBfusdAccountParams,
    ) -> anyhow::Result<RestApiResponse<models::GetBfusdAccountResponse>> {
        let GetBfusdAccountParams { 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::GetBfusdAccountResponse>(
            &self.configuration,
            "/sapi/v1/bfusd/account",
            reqwest::Method::GET,
            query_params,
            body_params,
            if HAS_TIME_UNIT {
                self.configuration.time_unit
            } else {
                None
            },
            true,
        )
        .await
    }

    async fn get_bfusd_quota_details(
        &self,
        params: GetBfusdQuotaDetailsParams,
    ) -> anyhow::Result<RestApiResponse<models::GetBfusdQuotaDetailsResponse>> {
        let GetBfusdQuotaDetailsParams { 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::GetBfusdQuotaDetailsResponse>(
            &self.configuration,
            "/sapi/v1/bfusd/quota",
            reqwest::Method::GET,
            query_params,
            body_params,
            if HAS_TIME_UNIT {
                self.configuration.time_unit
            } else {
                None
            },
            true,
        )
        .await
    }

    async fn get_bfusd_rate_history(
        &self,
        params: GetBfusdRateHistoryParams,
    ) -> anyhow::Result<RestApiResponse<models::GetBfusdRateHistoryResponse>> {
        let GetBfusdRateHistoryParams {
            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::GetBfusdRateHistoryResponse>(
            &self.configuration,
            "/sapi/v1/bfusd/history/rateHistory",
            reqwest::Method::GET,
            query_params,
            body_params,
            if HAS_TIME_UNIT {
                self.configuration.time_unit
            } else {
                None
            },
            true,
        )
        .await
    }

    async fn get_bfusd_redemption_history(
        &self,
        params: GetBfusdRedemptionHistoryParams,
    ) -> anyhow::Result<RestApiResponse<models::GetBfusdRedemptionHistoryResponse>> {
        let GetBfusdRedemptionHistoryParams {
            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::GetBfusdRedemptionHistoryResponse>(
            &self.configuration,
            "/sapi/v1/bfusd/history/redemptionHistory",
            reqwest::Method::GET,
            query_params,
            body_params,
            if HAS_TIME_UNIT {
                self.configuration.time_unit
            } else {
                None
            },
            true,
        )
        .await
    }

    async fn get_bfusd_rewards_history(
        &self,
        params: GetBfusdRewardsHistoryParams,
    ) -> anyhow::Result<RestApiResponse<models::GetBfusdRewardsHistoryResponse>> {
        let GetBfusdRewardsHistoryParams {
            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::GetBfusdRewardsHistoryResponse>(
            &self.configuration,
            "/sapi/v1/bfusd/history/rewardsHistory",
            reqwest::Method::GET,
            query_params,
            body_params,
            if HAS_TIME_UNIT {
                self.configuration.time_unit
            } else {
                None
            },
            true,
        )
        .await
    }

    async fn get_bfusd_subscription_history(
        &self,
        params: GetBfusdSubscriptionHistoryParams,
    ) -> anyhow::Result<RestApiResponse<models::GetBfusdSubscriptionHistoryResponse>> {
        let GetBfusdSubscriptionHistoryParams {
            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::GetBfusdSubscriptionHistoryResponse>(
            &self.configuration,
            "/sapi/v1/bfusd/history/subscriptionHistory",
            reqwest::Method::GET,
            query_params,
            body_params,
            if HAS_TIME_UNIT {
                self.configuration.time_unit
            } else {
                None
            },
            true,
        )
        .await
    }

    async fn redeem_bfusd(
        &self,
        params: RedeemBfusdParams,
    ) -> anyhow::Result<RestApiResponse<models::RedeemBfusdResponse>> {
        let RedeemBfusdParams {
            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::RedeemBfusdResponse>(
            &self.configuration,
            "/sapi/v1/bfusd/redeem",
            reqwest::Method::POST,
            query_params,
            body_params,
            if HAS_TIME_UNIT {
                self.configuration.time_unit
            } else {
                None
            },
            true,
        )
        .await
    }

    async fn subscribe_bfusd(
        &self,
        params: SubscribeBfusdParams,
    ) -> anyhow::Result<RestApiResponse<models::SubscribeBfusdResponse>> {
        let SubscribeBfusdParams {
            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::SubscribeBfusdResponse>(
            &self.configuration,
            "/sapi/v1/bfusd/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 MockBfusdApiClient {
        force_error: bool,
    }

    #[async_trait]
    impl BfusdApi for MockBfusdApiClient {
        async fn get_bfusd_account(
            &self,
            _params: GetBfusdAccountParams,
        ) -> anyhow::Result<RestApiResponse<models::GetBfusdAccountResponse>> {
            if self.force_error {
                return Err(ConnectorError::ConnectorClientError {
                    msg: "ResponseError".to_string(),
                    code: None,
                }
                .into());
            }

            let resp_json: Value = serde_json::from_str(
                r#"{"bfusdAmount":"100","usdtProfit":"11.00","bfusdProfit":"1.81"}"#,
            )
            .unwrap();
            let dummy_response: models::GetBfusdAccountResponse =
                serde_json::from_value(resp_json.clone())
                    .expect("should parse into models::GetBfusdAccountResponse");

            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_bfusd_quota_details(
            &self,
            _params: GetBfusdQuotaDetailsParams,
        ) -> anyhow::Result<RestApiResponse<models::GetBfusdQuotaDetailsResponse>> {
            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":{"leftQuota":"1000"},"fastRedemptionQuota":{"leftQuota":"2","minimum":"0.1","fee":"0.001","freeQuota":"100"},"standardRedemptionQuota":{"leftQuota":"2","minimum":"0.1","fee":"0.0005","redeemPeriod":3}}"#).unwrap();
            let dummy_response: models::GetBfusdQuotaDetailsResponse =
                serde_json::from_value(resp_json.clone())
                    .expect("should parse into models::GetBfusdQuotaDetailsResponse");

            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_bfusd_rate_history(
            &self,
            _params: GetBfusdRateHistoryParams,
        ) -> anyhow::Result<RestApiResponse<models::GetBfusdRateHistoryResponse>> {
            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::GetBfusdRateHistoryResponse =
                serde_json::from_value(resp_json.clone())
                    .expect("should parse into models::GetBfusdRateHistoryResponse");

            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_bfusd_redemption_history(
            &self,
            _params: GetBfusdRedemptionHistoryParams,
        ) -> anyhow::Result<RestApiResponse<models::GetBfusdRedemptionHistoryResponse>> {
            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":"BFUSD","amount":"51","receiveAsset":"USDT","receiveAmount":"50","fee":"1","arrivalTime":1575018510000,"status":"SUCCESS"}],"total":1}"#).unwrap();
            let dummy_response: models::GetBfusdRedemptionHistoryResponse =
                serde_json::from_value(resp_json.clone())
                    .expect("should parse into models::GetBfusdRedemptionHistoryResponse");

            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_bfusd_rewards_history(
            &self,
            _params: GetBfusdRewardsHistoryParams,
        ) -> anyhow::Result<RestApiResponse<models::GetBfusdRewardsHistoryResponse>> {
            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,"rewardAsset":"BFUSD","rewardsAmount":"1","BFUSDPosition":"100","annualPercentageRate":"0.0418"}],"total":1}"#).unwrap();
            let dummy_response: models::GetBfusdRewardsHistoryResponse =
                serde_json::from_value(resp_json.clone())
                    .expect("should parse into models::GetBfusdRewardsHistoryResponse");

            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_bfusd_subscription_history(
            &self,
            _params: GetBfusdSubscriptionHistoryParams,
        ) -> anyhow::Result<RestApiResponse<models::GetBfusdSubscriptionHistoryResponse>> {
            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":"USDT","amount":"100","receiveAsset":"BFUSD","receiveAmount":"100","status":"SUCCESS"}],"total":1}"#).unwrap();
            let dummy_response: models::GetBfusdSubscriptionHistoryResponse =
                serde_json::from_value(resp_json.clone())
                    .expect("should parse into models::GetBfusdSubscriptionHistoryResponse");

            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_bfusd(
            &self,
            _params: RedeemBfusdParams,
        ) -> anyhow::Result<RestApiResponse<models::RedeemBfusdResponse>> {
            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::RedeemBfusdResponse =
                serde_json::from_value(resp_json.clone())
                    .expect("should parse into models::RedeemBfusdResponse");

            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_bfusd(
            &self,
            _params: SubscribeBfusdParams,
        ) -> anyhow::Result<RestApiResponse<models::SubscribeBfusdResponse>> {
            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,"bfusdAmount":"0.22091092"}"#).unwrap();
            let dummy_response: models::SubscribeBfusdResponse =
                serde_json::from_value(resp_json.clone())
                    .expect("should parse into models::SubscribeBfusdResponse");

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

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

            let resp_json: Value = serde_json::from_str(
                r#"{"bfusdAmount":"100","usdtProfit":"11.00","bfusdProfit":"1.81"}"#,
            )
            .unwrap();
            let expected_response: models::GetBfusdAccountResponse =
                serde_json::from_value(resp_json.clone())
                    .expect("should parse into models::GetBfusdAccountResponse");

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

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

            let resp_json: Value = serde_json::from_str(
                r#"{"bfusdAmount":"100","usdtProfit":"11.00","bfusdProfit":"1.81"}"#,
            )
            .unwrap();
            let expected_response: models::GetBfusdAccountResponse =
                serde_json::from_value(resp_json.clone())
                    .expect("should parse into models::GetBfusdAccountResponse");

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

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

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

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

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

            let resp_json: Value = serde_json::from_str(r#"{"subscriptionQuota":{"leftQuota":"1000"},"fastRedemptionQuota":{"leftQuota":"2","minimum":"0.1","fee":"0.001","freeQuota":"100"},"standardRedemptionQuota":{"leftQuota":"2","minimum":"0.1","fee":"0.0005","redeemPeriod":3}}"#).unwrap();
            let expected_response : models::GetBfusdQuotaDetailsResponse = serde_json::from_value(resp_json.clone()).expect("should parse into models::GetBfusdQuotaDetailsResponse");

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

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

            let resp_json: Value = serde_json::from_str(r#"{"subscriptionQuota":{"leftQuota":"1000"},"fastRedemptionQuota":{"leftQuota":"2","minimum":"0.1","fee":"0.001","freeQuota":"100"},"standardRedemptionQuota":{"leftQuota":"2","minimum":"0.1","fee":"0.0005","redeemPeriod":3}}"#).unwrap();
            let expected_response : models::GetBfusdQuotaDetailsResponse = serde_json::from_value(resp_json.clone()).expect("should parse into models::GetBfusdQuotaDetailsResponse");

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

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

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

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

            let params = GetBfusdRateHistoryParams::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::GetBfusdRateHistoryResponse =
                serde_json::from_value(resp_json.clone())
                    .expect("should parse into models::GetBfusdRateHistoryResponse");

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

            let params = GetBfusdRateHistoryParams::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::GetBfusdRateHistoryResponse =
                serde_json::from_value(resp_json.clone())
                    .expect("should parse into models::GetBfusdRateHistoryResponse");

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

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

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

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

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

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

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

            let params = GetBfusdRedemptionHistoryParams::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":"BFUSD","amount":"51","receiveAsset":"USDT","receiveAmount":"50","fee":"1","arrivalTime":1575018510000,"status":"SUCCESS"}],"total":1}"#).unwrap();
            let expected_response : models::GetBfusdRedemptionHistoryResponse = serde_json::from_value(resp_json.clone()).expect("should parse into models::GetBfusdRedemptionHistoryResponse");

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

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

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

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

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

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

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

            let params = GetBfusdRewardsHistoryParams::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,"rewardAsset":"BFUSD","rewardsAmount":"1","BFUSDPosition":"100","annualPercentageRate":"0.0418"}],"total":1}"#).unwrap();
            let expected_response : models::GetBfusdRewardsHistoryResponse = serde_json::from_value(resp_json.clone()).expect("should parse into models::GetBfusdRewardsHistoryResponse");

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

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

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

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

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

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

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

            let params = GetBfusdSubscriptionHistoryParams::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":"USDT","amount":"100","receiveAsset":"BFUSD","receiveAmount":"100","status":"SUCCESS"}],"total":1}"#).unwrap();
            let expected_response : models::GetBfusdSubscriptionHistoryResponse = serde_json::from_value(resp_json.clone()).expect("should parse into models::GetBfusdSubscriptionHistoryResponse");

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

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

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

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

            let params = RedeemBfusdParams::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::RedeemBfusdResponse = serde_json::from_value(resp_json.clone()).expect("should parse into models::RedeemBfusdResponse");

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

            let params = RedeemBfusdParams::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::RedeemBfusdResponse = serde_json::from_value(resp_json.clone()).expect("should parse into models::RedeemBfusdResponse");

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

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

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

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

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

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

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

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

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

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

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

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