/*
 * 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 MarketDataApi: Send + Sync {
    async fn get_dual_investment_product_list(
        &self,
        params: GetDualInvestmentProductListParams,
    ) -> anyhow::Result<RestApiResponse<models::GetDualInvestmentProductListResponse>>;
}

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

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

/// Request parameters for the [`get_dual_investment_product_list`] operation.
///
/// This struct holds all of the inputs you can pass when calling
/// [`get_dual_investment_product_list`](#method.get_dual_investment_product_list).
#[derive(Clone, Debug, Builder)]
#[builder(pattern = "owned", build_fn(error = "ParamBuildError"))]
pub struct GetDualInvestmentProductListParams {
    /// Input CALL or PUT
    ///
    /// This field is **required.
    #[builder(setter(into))]
    pub option_type: String,
    /// Target exercised asset, e.g.: if you subscribe to a high sell product (call option), you should input: `optionType`:CALL,`exercisedCoin`:USDT,`investCoin`:BNB; if you subscribe to a low buy product (put option), you should input: `optionType`:PUT,`exercisedCoin`:BNB,`investCoin`:USDT
    ///
    /// This field is **required.
    #[builder(setter(into))]
    pub exercised_coin: String,
    /// Asset used for subscribing, e.g.: if you subscribe to a high sell product (call option), you should input: `optionType`:CALL,`exercisedCoin`:USDT,`investCoin`:BNB; if you subscribe to a low buy product (put option), you should input: `optionType`:PUT,`exercisedCoin`:BNB,`investCoin`:USDT
    ///
    /// This field is **required.
    #[builder(setter(into))]
    pub invest_coin: 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 GetDualInvestmentProductListParams {
    /// Create a builder for [`get_dual_investment_product_list`].
    ///
    /// Required parameters:
    ///
    /// * `option_type` — Input CALL or PUT
    /// * `exercised_coin` — Target exercised asset, e.g.: if you subscribe to a high sell product (call option), you should input: `optionType`:CALL,`exercisedCoin`:USDT,`investCoin`:BNB; if you subscribe to a low buy product (put option), you should input: `optionType`:PUT,`exercisedCoin`:BNB,`investCoin`:USDT
    /// * `invest_coin` — Asset used for subscribing, e.g.: if you subscribe to a high sell product (call option), you should input: `optionType`:CALL,`exercisedCoin`:USDT,`investCoin`:BNB; if you subscribe to a low buy product (put option), you should input: `optionType`:PUT,`exercisedCoin`:BNB,`investCoin`:USDT
    ///
    #[must_use]
    pub fn builder(
        option_type: String,
        exercised_coin: String,
        invest_coin: String,
    ) -> GetDualInvestmentProductListParamsBuilder {
        GetDualInvestmentProductListParamsBuilder::default()
            .option_type(option_type)
            .exercised_coin(exercised_coin)
            .invest_coin(invest_coin)
    }
}

#[async_trait]
impl MarketDataApi for MarketDataApiClient {
    async fn get_dual_investment_product_list(
        &self,
        params: GetDualInvestmentProductListParams,
    ) -> anyhow::Result<RestApiResponse<models::GetDualInvestmentProductListResponse>> {
        let GetDualInvestmentProductListParams {
            option_type,
            exercised_coin,
            invest_coin,
            page_size,
            page_index,
            recv_window,
        } = params;

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

        query_params.insert("optionType".to_string(), json!(option_type));

        query_params.insert("exercisedCoin".to_string(), json!(exercised_coin));

        query_params.insert("investCoin".to_string(), json!(invest_coin));

        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::GetDualInvestmentProductListResponse>(
            &self.configuration,
            "/sapi/v1/dci/product/list",
            reqwest::Method::GET,
            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 MockMarketDataApiClient {
        force_error: bool,
    }

    #[async_trait]
    impl MarketDataApi for MockMarketDataApiClient {
        async fn get_dual_investment_product_list(
            &self,
            _params: GetDualInvestmentProductListParams,
        ) -> anyhow::Result<RestApiResponse<models::GetDualInvestmentProductListResponse>> {
            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":"741590","investCoin":"USDT","exercisedCoin":"BNB","strikePrice":"380","duration":4,"settleDate":1709020800000,"purchaseDecimal":8,"purchaseEndTime":1708934400000,"canPurchase":true,"apr":"0.6076","orderId":8257205859,"minAmount":"0.1","maxAmount":"25265.7","createTimestamp":1708560084000,"optionType":"PUT","isAutoCompoundEnable":true,"autoCompoundPlanList":["STANDARD","ADVANCE"]}]}"#).unwrap();
            let dummy_response: models::GetDualInvestmentProductListResponse =
                serde_json::from_value(resp_json.clone())
                    .expect("should parse into models::GetDualInvestmentProductListResponse");

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

            let params = GetDualInvestmentProductListParams::builder("option_type_example".to_string(),"exercised_coin_example".to_string(),"invest_coin_example".to_string(),).build().unwrap();

            let resp_json: Value = serde_json::from_str(r#"{"total":1,"list":[{"id":"741590","investCoin":"USDT","exercisedCoin":"BNB","strikePrice":"380","duration":4,"settleDate":1709020800000,"purchaseDecimal":8,"purchaseEndTime":1708934400000,"canPurchase":true,"apr":"0.6076","orderId":8257205859,"minAmount":"0.1","maxAmount":"25265.7","createTimestamp":1708560084000,"optionType":"PUT","isAutoCompoundEnable":true,"autoCompoundPlanList":["STANDARD","ADVANCE"]}]}"#).unwrap();
            let expected_response : models::GetDualInvestmentProductListResponse = serde_json::from_value(resp_json.clone()).expect("should parse into models::GetDualInvestmentProductListResponse");

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

            let params = GetDualInvestmentProductListParams::builder("option_type_example".to_string(),"exercised_coin_example".to_string(),"invest_coin_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":"741590","investCoin":"USDT","exercisedCoin":"BNB","strikePrice":"380","duration":4,"settleDate":1709020800000,"purchaseDecimal":8,"purchaseEndTime":1708934400000,"canPurchase":true,"apr":"0.6076","orderId":8257205859,"minAmount":"0.1","maxAmount":"25265.7","createTimestamp":1708560084000,"optionType":"PUT","isAutoCompoundEnable":true,"autoCompoundPlanList":["STANDARD","ADVANCE"]}]}"#).unwrap();
            let expected_response : models::GetDualInvestmentProductListResponse = serde_json::from_value(resp_json.clone()).expect("should parse into models::GetDualInvestmentProductListResponse");

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

            let params = GetDualInvestmentProductListParams::builder(
                "option_type_example".to_string(),
                "exercised_coin_example".to_string(),
                "invest_coin_example".to_string(),
            )
            .build()
            .unwrap();

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