/*
 * Binance Dual Investment REST API
 *
 * OpenAPI Specification for the Binance Dual Investment 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::dual_investment::rest_api::models;

const HAS_TIME_UNIT: bool = false;

#[async_trait]
pub trait TradeApi: Send + Sync {
    async fn change_auto_compound_status(
        &self,
        params: ChangeAutoCompoundStatusParams,
    ) -> anyhow::Result<RestApiResponse<models::ChangeAutoCompoundStatusResponse>>;
    async fn check_dual_investment_accounts(
        &self,
        params: CheckDualInvestmentAccountsParams,
    ) -> anyhow::Result<RestApiResponse<models::CheckDualInvestmentAccountsResponse>>;
    async fn get_dual_investment_positions(
        &self,
        params: GetDualInvestmentPositionsParams,
    ) -> anyhow::Result<RestApiResponse<models::GetDualInvestmentPositionsResponse>>;
    async fn subscribe_dual_investment_products(
        &self,
        params: SubscribeDualInvestmentProductsParams,
    ) -> anyhow::Result<RestApiResponse<models::SubscribeDualInvestmentProductsResponse>>;
}

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

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

/// Request parameters for the [`change_auto_compound_status`] operation.
///
/// This struct holds all of the inputs you can pass when calling
/// [`change_auto_compound_status`](#method.change_auto_compound_status).
#[derive(Clone, Debug, Builder)]
#[builder(pattern = "owned", build_fn(error = "ParamBuildError"))]
pub struct ChangeAutoCompoundStatusParams {
    /// Get positionId from `/sapi/v1/dci/product/positions`
    ///
    /// This field is **required.
    #[builder(setter(into))]
    pub position_id: String,
    ///
    /// The `auto_compound_plan` parameter.
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub auto_compound_plan: Option<String>,
    /// The value cannot be greater than 60000
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub recv_window: Option<i64>,
}

impl ChangeAutoCompoundStatusParams {
    /// Create a builder for [`change_auto_compound_status`].
    ///
    /// Required parameters:
    ///
    /// * `position_id` — Get positionId from `/sapi/v1/dci/product/positions`
    ///
    #[must_use]
    pub fn builder(position_id: String) -> ChangeAutoCompoundStatusParamsBuilder {
        ChangeAutoCompoundStatusParamsBuilder::default().position_id(position_id)
    }
}
/// Request parameters for the [`check_dual_investment_accounts`] operation.
///
/// This struct holds all of the inputs you can pass when calling
/// [`check_dual_investment_accounts`](#method.check_dual_investment_accounts).
#[derive(Clone, Debug, Builder, Default)]
#[builder(pattern = "owned", build_fn(error = "ParamBuildError"))]
pub struct CheckDualInvestmentAccountsParams {
    /// The value cannot be greater than 60000
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub recv_window: Option<i64>,
}

impl CheckDualInvestmentAccountsParams {
    /// Create a builder for [`check_dual_investment_accounts`].
    ///
    #[must_use]
    pub fn builder() -> CheckDualInvestmentAccountsParamsBuilder {
        CheckDualInvestmentAccountsParamsBuilder::default()
    }
}
/// Request parameters for the [`get_dual_investment_positions`] operation.
///
/// This struct holds all of the inputs you can pass when calling
/// [`get_dual_investment_positions`](#method.get_dual_investment_positions).
#[derive(Clone, Debug, Builder, Default)]
#[builder(pattern = "owned", build_fn(error = "ParamBuildError"))]
pub struct GetDualInvestmentPositionsParams {
    /// `PENDING`:Products are purchasing, will give results later;`PURCHASE_SUCCESS`:purchase successfully;`SETTLED`: Products are finish settling;`PURCHASE_FAIL`:fail to purchase;`REFUNDING`:refund ongoing;`REFUND_SUCCESS`:refund to spot account successfully; `SETTLING`:Products are settling. If don't fill this field, will response all the position status.
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub status: Option<String>,
    /// Default: 10, Maximum: 100
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub page_size: Option<i64>,
    /// Default: 1
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub page_index: Option<i64>,
    /// The value cannot be greater than 60000
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub recv_window: Option<i64>,
}

impl GetDualInvestmentPositionsParams {
    /// Create a builder for [`get_dual_investment_positions`].
    ///
    #[must_use]
    pub fn builder() -> GetDualInvestmentPositionsParamsBuilder {
        GetDualInvestmentPositionsParamsBuilder::default()
    }
}
/// Request parameters for the [`subscribe_dual_investment_products`] operation.
///
/// This struct holds all of the inputs you can pass when calling
/// [`subscribe_dual_investment_products`](#method.subscribe_dual_investment_products).
#[derive(Clone, Debug, Builder)]
#[builder(pattern = "owned", build_fn(error = "ParamBuildError"))]
pub struct SubscribeDualInvestmentProductsParams {
    /// get id from `/sapi/v1/dci/product/list`
    ///
    /// This field is **required.
    #[builder(setter(into))]
    pub id: String,
    /// get orderId from `/sapi/v1/dci/product/list`
    ///
    /// This field is **required.
    #[builder(setter(into))]
    pub order_id: String,
    /// the amount for subscribing
    ///
    /// This field is **required.
    #[builder(setter(into))]
    pub deposit_amount: rust_decimal::Decimal,
    /// `NONE`: switch off the plan, `STANDARD`:standard plan,`ADVANCED`:advanced plan
    ///
    /// This field is **required.
    #[builder(setter(into))]
    pub auto_compound_plan: String,
    /// The value cannot be greater than 60000
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub recv_window: Option<i64>,
}

impl SubscribeDualInvestmentProductsParams {
    /// Create a builder for [`subscribe_dual_investment_products`].
    ///
    /// Required parameters:
    ///
    /// * `id` — get id from `/sapi/v1/dci/product/list`
    /// * `order_id` — get orderId from `/sapi/v1/dci/product/list`
    /// * `deposit_amount` — the amount for subscribing
    /// * `auto_compound_plan` — `NONE`: switch off the plan, `STANDARD`:standard plan,`ADVANCED`:advanced plan
    ///
    #[must_use]
    pub fn builder(
        id: String,
        order_id: String,
        deposit_amount: rust_decimal::Decimal,
        auto_compound_plan: String,
    ) -> SubscribeDualInvestmentProductsParamsBuilder {
        SubscribeDualInvestmentProductsParamsBuilder::default()
            .id(id)
            .order_id(order_id)
            .deposit_amount(deposit_amount)
            .auto_compound_plan(auto_compound_plan)
    }
}

#[async_trait]
impl TradeApi for TradeApiClient {
    async fn change_auto_compound_status(
        &self,
        params: ChangeAutoCompoundStatusParams,
    ) -> anyhow::Result<RestApiResponse<models::ChangeAutoCompoundStatusResponse>> {
        let ChangeAutoCompoundStatusParams {
            position_id,
            auto_compound_plan,
            recv_window,
        } = params;

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

        query_params.insert("positionId".to_string(), json!(position_id));

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

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

        send_request::<models::ChangeAutoCompoundStatusResponse>(
            &self.configuration,
            "/sapi/v1/dci/product/auto_compound/edit-status",
            reqwest::Method::POST,
            query_params,
            body_params,
            if HAS_TIME_UNIT {
                self.configuration.time_unit
            } else {
                None
            },
            true,
        )
        .await
    }

    async fn check_dual_investment_accounts(
        &self,
        params: CheckDualInvestmentAccountsParams,
    ) -> anyhow::Result<RestApiResponse<models::CheckDualInvestmentAccountsResponse>> {
        let CheckDualInvestmentAccountsParams { 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::CheckDualInvestmentAccountsResponse>(
            &self.configuration,
            "/sapi/v1/dci/product/accounts",
            reqwest::Method::GET,
            query_params,
            body_params,
            if HAS_TIME_UNIT {
                self.configuration.time_unit
            } else {
                None
            },
            true,
        )
        .await
    }

    async fn get_dual_investment_positions(
        &self,
        params: GetDualInvestmentPositionsParams,
    ) -> anyhow::Result<RestApiResponse<models::GetDualInvestmentPositionsResponse>> {
        let GetDualInvestmentPositionsParams {
            status,
            page_size,
            page_index,
            recv_window,
        } = params;

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

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

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

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

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

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

    async fn subscribe_dual_investment_products(
        &self,
        params: SubscribeDualInvestmentProductsParams,
    ) -> anyhow::Result<RestApiResponse<models::SubscribeDualInvestmentProductsResponse>> {
        let SubscribeDualInvestmentProductsParams {
            id,
            order_id,
            deposit_amount,
            auto_compound_plan,
            recv_window,
        } = params;

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

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

        query_params.insert("orderId".to_string(), json!(order_id));

        query_params.insert("depositAmount".to_string(), json!(deposit_amount));

        query_params.insert("autoCompoundPlan".to_string(), json!(auto_compound_plan));

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

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

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

    #[async_trait]
    impl TradeApi for MockTradeApiClient {
        async fn change_auto_compound_status(
            &self,
            _params: ChangeAutoCompoundStatusParams,
        ) -> anyhow::Result<RestApiResponse<models::ChangeAutoCompoundStatusResponse>> {
            if self.force_error {
                return Err(ConnectorError::ConnectorClientError {
                    msg: "ResponseError".to_string(),
                    code: None,
                }
                .into());
            }

            let resp_json: Value =
                serde_json::from_str(r#"{"positionId":"123456789","autoCompoundPlan":"ADVANCED"}"#)
                    .unwrap();
            let dummy_response: models::ChangeAutoCompoundStatusResponse =
                serde_json::from_value(resp_json.clone())
                    .expect("should parse into models::ChangeAutoCompoundStatusResponse");

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

            let resp_json: Value = serde_json::from_str(
                r#"{"totalAmountInBTC":"0.01067982","totalAmountInUSDT":"77.13289230"}"#,
            )
            .unwrap();
            let dummy_response: models::CheckDualInvestmentAccountsResponse =
                serde_json::from_value(resp_json.clone())
                    .expect("should parse into models::CheckDualInvestmentAccountsResponse");

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

            let resp_json: Value = serde_json::from_str(r#"{"total":1,"list":[{"id":"10160533","investCoin":"USDT","exercisedCoin":"BNB","subscriptionAmount":"0.5","strikePrice":"330","duration":4,"settleDate":1708416000000,"purchaseStatus":"PURCHASE_SUCCESS","apr":"0.0365","orderId":7973677530,"purchaseEndTime":1708329600000,"optionType":"PUT","autoCompoundPlan":"STANDARD"}]}"#).unwrap();
            let dummy_response: models::GetDualInvestmentPositionsResponse =
                serde_json::from_value(resp_json.clone())
                    .expect("should parse into models::GetDualInvestmentPositionsResponse");

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

            let resp_json: Value = serde_json::from_str(r#"{"positionId":10208824,"investCoin":"BNB","exercisedCoin":"USDT","subscriptionAmount":"0.002","duration":4,"autoCompoundPlan":"STANDARD","strikePrice":"380","settleDate":1709020800000,"purchaseStatus":"PURCHASE_SUCCESS","apr":"0.7397","orderId":8259117597,"purchaseTime":1708677583874,"optionType":"CALL"}"#).unwrap();
            let dummy_response: models::SubscribeDualInvestmentProductsResponse =
                serde_json::from_value(resp_json.clone())
                    .expect("should parse into models::SubscribeDualInvestmentProductsResponse");

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

            let params = ChangeAutoCompoundStatusParams::builder("1".to_string())
                .build()
                .unwrap();

            let resp_json: Value =
                serde_json::from_str(r#"{"positionId":"123456789","autoCompoundPlan":"ADVANCED"}"#)
                    .unwrap();
            let expected_response: models::ChangeAutoCompoundStatusResponse =
                serde_json::from_value(resp_json.clone())
                    .expect("should parse into models::ChangeAutoCompoundStatusResponse");

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

            let params = ChangeAutoCompoundStatusParams::builder("1".to_string())
                .auto_compound_plan("auto_compound_plan_example".to_string())
                .recv_window(5000)
                .build()
                .unwrap();

            let resp_json: Value =
                serde_json::from_str(r#"{"positionId":"123456789","autoCompoundPlan":"ADVANCED"}"#)
                    .unwrap();
            let expected_response: models::ChangeAutoCompoundStatusResponse =
                serde_json::from_value(resp_json.clone())
                    .expect("should parse into models::ChangeAutoCompoundStatusResponse");

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

            let params = ChangeAutoCompoundStatusParams::builder("1".to_string())
                .build()
                .unwrap();

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

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

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

            let resp_json: Value = serde_json::from_str(
                r#"{"totalAmountInBTC":"0.01067982","totalAmountInUSDT":"77.13289230"}"#,
            )
            .unwrap();
            let expected_response: models::CheckDualInvestmentAccountsResponse =
                serde_json::from_value(resp_json.clone())
                    .expect("should parse into models::CheckDualInvestmentAccountsResponse");

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

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

            let resp_json: Value = serde_json::from_str(
                r#"{"totalAmountInBTC":"0.01067982","totalAmountInUSDT":"77.13289230"}"#,
            )
            .unwrap();
            let expected_response: models::CheckDualInvestmentAccountsResponse =
                serde_json::from_value(resp_json.clone())
                    .expect("should parse into models::CheckDualInvestmentAccountsResponse");

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

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

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

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

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

            let resp_json: Value = serde_json::from_str(r#"{"total":1,"list":[{"id":"10160533","investCoin":"USDT","exercisedCoin":"BNB","subscriptionAmount":"0.5","strikePrice":"330","duration":4,"settleDate":1708416000000,"purchaseStatus":"PURCHASE_SUCCESS","apr":"0.0365","orderId":7973677530,"purchaseEndTime":1708329600000,"optionType":"PUT","autoCompoundPlan":"STANDARD"}]}"#).unwrap();
            let expected_response : models::GetDualInvestmentPositionsResponse = serde_json::from_value(resp_json.clone()).expect("should parse into models::GetDualInvestmentPositionsResponse");

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

            let params = GetDualInvestmentPositionsParams::builder().status("status_example".to_string()).page_size(10).page_index(1).recv_window(5000).build().unwrap();

            let resp_json: Value = serde_json::from_str(r#"{"total":1,"list":[{"id":"10160533","investCoin":"USDT","exercisedCoin":"BNB","subscriptionAmount":"0.5","strikePrice":"330","duration":4,"settleDate":1708416000000,"purchaseStatus":"PURCHASE_SUCCESS","apr":"0.0365","orderId":7973677530,"purchaseEndTime":1708329600000,"optionType":"PUT","autoCompoundPlan":"STANDARD"}]}"#).unwrap();
            let expected_response : models::GetDualInvestmentPositionsResponse = serde_json::from_value(resp_json.clone()).expect("should parse into models::GetDualInvestmentPositionsResponse");

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

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

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

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

            let params = SubscribeDualInvestmentProductsParams::builder("id_example".to_string(),"1".to_string(),dec!(1.0),"NONE".to_string(),).build().unwrap();

            let resp_json: Value = serde_json::from_str(r#"{"positionId":10208824,"investCoin":"BNB","exercisedCoin":"USDT","subscriptionAmount":"0.002","duration":4,"autoCompoundPlan":"STANDARD","strikePrice":"380","settleDate":1709020800000,"purchaseStatus":"PURCHASE_SUCCESS","apr":"0.7397","orderId":8259117597,"purchaseTime":1708677583874,"optionType":"CALL"}"#).unwrap();
            let expected_response : models::SubscribeDualInvestmentProductsResponse = serde_json::from_value(resp_json.clone()).expect("should parse into models::SubscribeDualInvestmentProductsResponse");

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

            let params = SubscribeDualInvestmentProductsParams::builder("id_example".to_string(),"1".to_string(),dec!(1.0),"NONE".to_string(),).recv_window(5000).build().unwrap();

            let resp_json: Value = serde_json::from_str(r#"{"positionId":10208824,"investCoin":"BNB","exercisedCoin":"USDT","subscriptionAmount":"0.002","duration":4,"autoCompoundPlan":"STANDARD","strikePrice":"380","settleDate":1709020800000,"purchaseStatus":"PURCHASE_SUCCESS","apr":"0.7397","orderId":8259117597,"purchaseTime":1708677583874,"optionType":"CALL"}"#).unwrap();
            let expected_response : models::SubscribeDualInvestmentProductsResponse = serde_json::from_value(resp_json.clone()).expect("should parse into models::SubscribeDualInvestmentProductsResponse");

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

            let params = SubscribeDualInvestmentProductsParams::builder(
                "id_example".to_string(),
                "1".to_string(),
                dec!(1.0),
                "NONE".to_string(),
            )
            .build()
            .unwrap();

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