/*
 * Binance Derivatives Trading Portfolio Margin Pro REST API
 *
 * OpenAPI Specification for the Binance Derivatives Trading Portfolio Margin Pro 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::derivatives_trading_portfolio_margin_pro::rest_api::models;

const HAS_TIME_UNIT: bool = false;

#[async_trait]
pub trait MarketDataApi: Send + Sync {
    async fn get_portfolio_margin_asset_leverage(
        &self,
    ) -> anyhow::Result<RestApiResponse<Vec<models::GetPortfolioMarginAssetLeverageResponseInner>>>;
    async fn portfolio_margin_collateral_rate(
        &self,
    ) -> anyhow::Result<RestApiResponse<Vec<models::PortfolioMarginCollateralRateResponseInner>>>;
    async fn portfolio_margin_pro_tiered_collateral_rate(
        &self,
        params: PortfolioMarginProTieredCollateralRateParams,
    ) -> anyhow::Result<
        RestApiResponse<Vec<models::PortfolioMarginProTieredCollateralRateResponseInner>>,
    >;
    async fn query_portfolio_margin_asset_index_price(
        &self,
        params: QueryPortfolioMarginAssetIndexPriceParams,
    ) -> anyhow::Result<
        RestApiResponse<Vec<models::QueryPortfolioMarginAssetIndexPriceResponseInner>>,
    >;
}

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

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

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

impl PortfolioMarginProTieredCollateralRateParams {
    /// Create a builder for [`portfolio_margin_pro_tiered_collateral_rate`].
    ///
    #[must_use]
    pub fn builder() -> PortfolioMarginProTieredCollateralRateParamsBuilder {
        PortfolioMarginProTieredCollateralRateParamsBuilder::default()
    }
}
/// Request parameters for the [`query_portfolio_margin_asset_index_price`] operation.
///
/// This struct holds all of the inputs you can pass when calling
/// [`query_portfolio_margin_asset_index_price`](#method.query_portfolio_margin_asset_index_price).
#[derive(Clone, Debug, Builder, Default)]
#[builder(pattern = "owned", build_fn(error = "ParamBuildError"))]
pub struct QueryPortfolioMarginAssetIndexPriceParams {
    ///
    /// The `asset` parameter.
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub asset: Option<String>,
}

impl QueryPortfolioMarginAssetIndexPriceParams {
    /// Create a builder for [`query_portfolio_margin_asset_index_price`].
    ///
    #[must_use]
    pub fn builder() -> QueryPortfolioMarginAssetIndexPriceParamsBuilder {
        QueryPortfolioMarginAssetIndexPriceParamsBuilder::default()
    }
}

#[async_trait]
impl MarketDataApi for MarketDataApiClient {
    async fn get_portfolio_margin_asset_leverage(
        &self,
    ) -> anyhow::Result<RestApiResponse<Vec<models::GetPortfolioMarginAssetLeverageResponseInner>>>
    {
        let query_params = BTreeMap::new();
        let body_params = BTreeMap::new();

        send_request::<Vec<models::GetPortfolioMarginAssetLeverageResponseInner>>(
            &self.configuration,
            "/sapi/v1/portfolio/margin-asset-leverage",
            reqwest::Method::GET,
            query_params,
            body_params,
            if HAS_TIME_UNIT {
                self.configuration.time_unit
            } else {
                None
            },
            true,
        )
        .await
    }

    async fn portfolio_margin_collateral_rate(
        &self,
    ) -> anyhow::Result<RestApiResponse<Vec<models::PortfolioMarginCollateralRateResponseInner>>>
    {
        let query_params = BTreeMap::new();
        let body_params = BTreeMap::new();

        send_request::<Vec<models::PortfolioMarginCollateralRateResponseInner>>(
            &self.configuration,
            "/sapi/v1/portfolio/collateralRate",
            reqwest::Method::GET,
            query_params,
            body_params,
            if HAS_TIME_UNIT {
                self.configuration.time_unit
            } else {
                None
            },
            false,
        )
        .await
    }

    async fn portfolio_margin_pro_tiered_collateral_rate(
        &self,
        params: PortfolioMarginProTieredCollateralRateParams,
    ) -> anyhow::Result<
        RestApiResponse<Vec<models::PortfolioMarginProTieredCollateralRateResponseInner>>,
    > {
        let PortfolioMarginProTieredCollateralRateParams { 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::<Vec<models::PortfolioMarginProTieredCollateralRateResponseInner>>(
            &self.configuration,
            "/sapi/v2/portfolio/collateralRate",
            reqwest::Method::GET,
            query_params,
            body_params,
            if HAS_TIME_UNIT {
                self.configuration.time_unit
            } else {
                None
            },
            true,
        )
        .await
    }

    async fn query_portfolio_margin_asset_index_price(
        &self,
        params: QueryPortfolioMarginAssetIndexPriceParams,
    ) -> anyhow::Result<
        RestApiResponse<Vec<models::QueryPortfolioMarginAssetIndexPriceResponseInner>>,
    > {
        let QueryPortfolioMarginAssetIndexPriceParams { asset } = 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));
        }

        send_request::<Vec<models::QueryPortfolioMarginAssetIndexPriceResponseInner>>(
            &self.configuration,
            "/sapi/v1/portfolio/asset-index-price",
            reqwest::Method::GET,
            query_params,
            body_params,
            if HAS_TIME_UNIT {
                self.configuration.time_unit
            } else {
                None
            },
            false,
        )
        .await
    }
}

#[cfg(all(test, feature = "derivatives_trading_portfolio_margin_pro"))]
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_portfolio_margin_asset_leverage(
            &self,
        ) -> anyhow::Result<
            RestApiResponse<Vec<models::GetPortfolioMarginAssetLeverageResponseInner>>,
        > {
            if self.force_error {
                return Err(ConnectorError::ConnectorClientError {
                    msg: "ResponseError".to_string(),
                    code: None,
                }
                .into());
            }

            let resp_json: Value = serde_json::from_str(
                r#"[{"asset":"USDC","leverage":10},{"asset":"USDT","leverage":10}]"#,
            )
            .unwrap();
            let dummy_response: Vec<models::GetPortfolioMarginAssetLeverageResponseInner> =
                serde_json::from_value(resp_json.clone()).expect(
                    "should parse into Vec<models::GetPortfolioMarginAssetLeverageResponseInner>",
                );

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

            let resp_json: Value = serde_json::from_str(r#"[{"asset":"USDC","collateralRate":"1.0000"},{"asset":"BUSD","collateralRate":"1.0000"}]"#).unwrap();
            let dummy_response: Vec<models::PortfolioMarginCollateralRateResponseInner> =
                serde_json::from_value(resp_json.clone()).expect(
                    "should parse into Vec<models::PortfolioMarginCollateralRateResponseInner>",
                );

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

            let resp_json: Value = serde_json::from_str(r#"[{"asset":"BNB","collateralInfo":[{"tierFloor":"0.0000","tierCap":"1000.0000","collateralRate":"1.0000","cum":"0.0000"},{"tierFloor":"1000.0000","tierCap":"2000.0000","collateralRate":"0.9000","cum":"0.0000"}]},{"asset":"USDT","collateralInfo":[{"tierFloor":"0.0000","tierCap":"1000.0000","collateralRate":"1.0000","cum":"0.0000"},{"tierFloor":"1000.0000","tierCap":"2000.0000","collateralRate":"0.9999","cum":"0.0000"}]}]"#).unwrap();
            let dummy_response : Vec<models::PortfolioMarginProTieredCollateralRateResponseInner> = serde_json::from_value(resp_json.clone()).expect("should parse into Vec<models::PortfolioMarginProTieredCollateralRateResponseInner>");

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

            let resp_json: Value = serde_json::from_str(
                r#"[{"asset":"BTC","assetIndexPrice":"28251.9136906","time":1683518338121}]"#,
            )
            .unwrap();
            let dummy_response : Vec<models::QueryPortfolioMarginAssetIndexPriceResponseInner> = serde_json::from_value(resp_json.clone()).expect("should parse into Vec<models::QueryPortfolioMarginAssetIndexPriceResponseInner>");

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

            let resp_json: Value = serde_json::from_str(
                r#"[{"asset":"USDC","leverage":10},{"asset":"USDT","leverage":10}]"#,
            )
            .unwrap();
            let expected_response: Vec<models::GetPortfolioMarginAssetLeverageResponseInner> =
                serde_json::from_value(resp_json.clone()).expect(
                    "should parse into Vec<models::GetPortfolioMarginAssetLeverageResponseInner>",
                );

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

            let resp_json: Value = serde_json::from_str(
                r#"[{"asset":"USDC","leverage":10},{"asset":"USDT","leverage":10}]"#,
            )
            .unwrap();
            let expected_response: Vec<models::GetPortfolioMarginAssetLeverageResponseInner> =
                serde_json::from_value(resp_json.clone()).expect(
                    "should parse into Vec<models::GetPortfolioMarginAssetLeverageResponseInner>",
                );

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

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

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


            let resp_json: Value = serde_json::from_str(r#"[{"asset":"USDC","collateralRate":"1.0000"},{"asset":"BUSD","collateralRate":"1.0000"}]"#).unwrap();
            let expected_response : Vec<models::PortfolioMarginCollateralRateResponseInner> = serde_json::from_value(resp_json.clone()).expect("should parse into Vec<models::PortfolioMarginCollateralRateResponseInner>");

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


            let resp_json: Value = serde_json::from_str(r#"[{"asset":"USDC","collateralRate":"1.0000"},{"asset":"BUSD","collateralRate":"1.0000"}]"#).unwrap();
            let expected_response : Vec<models::PortfolioMarginCollateralRateResponseInner> = serde_json::from_value(resp_json.clone()).expect("should parse into Vec<models::PortfolioMarginCollateralRateResponseInner>");

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

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

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

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

            let resp_json: Value = serde_json::from_str(r#"[{"asset":"BNB","collateralInfo":[{"tierFloor":"0.0000","tierCap":"1000.0000","collateralRate":"1.0000","cum":"0.0000"},{"tierFloor":"1000.0000","tierCap":"2000.0000","collateralRate":"0.9000","cum":"0.0000"}]},{"asset":"USDT","collateralInfo":[{"tierFloor":"0.0000","tierCap":"1000.0000","collateralRate":"1.0000","cum":"0.0000"},{"tierFloor":"1000.0000","tierCap":"2000.0000","collateralRate":"0.9999","cum":"0.0000"}]}]"#).unwrap();
            let expected_response : Vec<models::PortfolioMarginProTieredCollateralRateResponseInner> = serde_json::from_value(resp_json.clone()).expect("should parse into Vec<models::PortfolioMarginProTieredCollateralRateResponseInner>");

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

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

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

            let resp_json: Value = serde_json::from_str(r#"[{"asset":"BNB","collateralInfo":[{"tierFloor":"0.0000","tierCap":"1000.0000","collateralRate":"1.0000","cum":"0.0000"},{"tierFloor":"1000.0000","tierCap":"2000.0000","collateralRate":"0.9000","cum":"0.0000"}]},{"asset":"USDT","collateralInfo":[{"tierFloor":"0.0000","tierCap":"1000.0000","collateralRate":"1.0000","cum":"0.0000"},{"tierFloor":"1000.0000","tierCap":"2000.0000","collateralRate":"0.9999","cum":"0.0000"}]}]"#).unwrap();
            let expected_response : Vec<models::PortfolioMarginProTieredCollateralRateResponseInner> = serde_json::from_value(resp_json.clone()).expect("should parse into Vec<models::PortfolioMarginProTieredCollateralRateResponseInner>");

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

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

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

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

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

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

            let resp_json: Value = serde_json::from_str(r#"[{"asset":"BTC","assetIndexPrice":"28251.9136906","time":1683518338121}]"#).unwrap();
            let expected_response : Vec<models::QueryPortfolioMarginAssetIndexPriceResponseInner> = serde_json::from_value(resp_json.clone()).expect("should parse into Vec<models::QueryPortfolioMarginAssetIndexPriceResponseInner>");

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

            let params = QueryPortfolioMarginAssetIndexPriceParams::builder().asset("asset_example".to_string()).build().unwrap();

            let resp_json: Value = serde_json::from_str(r#"[{"asset":"BTC","assetIndexPrice":"28251.9136906","time":1683518338121}]"#).unwrap();
            let expected_response : Vec<models::QueryPortfolioMarginAssetIndexPriceResponseInner> = serde_json::from_value(resp_json.clone()).expect("should parse into Vec<models::QueryPortfolioMarginAssetIndexPriceResponseInner>");

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

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

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