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

const HAS_TIME_UNIT: bool = false;

#[async_trait]
pub trait SoftStakingApi: Send + Sync {
    async fn get_soft_staking_product_list(
        &self,
        params: GetSoftStakingProductListParams,
    ) -> anyhow::Result<RestApiResponse<models::GetSoftStakingProductListResponse>>;
    async fn get_soft_staking_rewards_history(
        &self,
        params: GetSoftStakingRewardsHistoryParams,
    ) -> anyhow::Result<RestApiResponse<models::GetSoftStakingRewardsHistoryResponse>>;
    async fn set_soft_staking(
        &self,
        params: SetSoftStakingParams,
    ) -> anyhow::Result<RestApiResponse<models::SetSoftStakingResponse>>;
}

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

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

/// Request parameters for the [`get_soft_staking_product_list`] operation.
///
/// This struct holds all of the inputs you can pass when calling
/// [`get_soft_staking_product_list`](#method.get_soft_staking_product_list).
#[derive(Clone, Debug, Builder, Default)]
#[builder(pattern = "owned", build_fn(error = "ParamBuildError"))]
pub struct GetSoftStakingProductListParams {
    /// WBETH or BETH, default to BETH
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub asset: Option<String>,
    /// Currently querying page. Start from 1. Default:1
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub current: Option<i64>,
    /// Default:10, Max:100
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub size: Option<i64>,
    ///
    /// The `recv_window` parameter.
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub recv_window: Option<i64>,
}

impl GetSoftStakingProductListParams {
    /// Create a builder for [`get_soft_staking_product_list`].
    ///
    #[must_use]
    pub fn builder() -> GetSoftStakingProductListParamsBuilder {
        GetSoftStakingProductListParamsBuilder::default()
    }
}
/// Request parameters for the [`get_soft_staking_rewards_history`] operation.
///
/// This struct holds all of the inputs you can pass when calling
/// [`get_soft_staking_rewards_history`](#method.get_soft_staking_rewards_history).
#[derive(Clone, Debug, Builder, Default)]
#[builder(pattern = "owned", build_fn(error = "ParamBuildError"))]
pub struct GetSoftStakingRewardsHistoryParams {
    /// WBETH or BETH, default to BETH
    ///
    /// 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. Start from 1. Default:1
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub current: Option<i64>,
    /// Default:10, Max:100
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub size: Option<i64>,
    ///
    /// The `recv_window` parameter.
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub recv_window: Option<i64>,
}

impl GetSoftStakingRewardsHistoryParams {
    /// Create a builder for [`get_soft_staking_rewards_history`].
    ///
    #[must_use]
    pub fn builder() -> GetSoftStakingRewardsHistoryParamsBuilder {
        GetSoftStakingRewardsHistoryParamsBuilder::default()
    }
}
/// Request parameters for the [`set_soft_staking`] operation.
///
/// This struct holds all of the inputs you can pass when calling
/// [`set_soft_staking`](#method.set_soft_staking).
#[derive(Clone, Debug, Builder)]
#[builder(pattern = "owned", build_fn(error = "ParamBuildError"))]
pub struct SetSoftStakingParams {
    /// true or false
    ///
    /// This field is **required.
    #[builder(setter(into))]
    pub soft_staking: bool,
    ///
    /// The `recv_window` parameter.
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub recv_window: Option<i64>,
}

impl SetSoftStakingParams {
    /// Create a builder for [`set_soft_staking`].
    ///
    /// Required parameters:
    ///
    /// * `soft_staking` — true or false
    ///
    #[must_use]
    pub fn builder(soft_staking: bool) -> SetSoftStakingParamsBuilder {
        SetSoftStakingParamsBuilder::default().soft_staking(soft_staking)
    }
}

#[async_trait]
impl SoftStakingApi for SoftStakingApiClient {
    async fn get_soft_staking_product_list(
        &self,
        params: GetSoftStakingProductListParams,
    ) -> anyhow::Result<RestApiResponse<models::GetSoftStakingProductListResponse>> {
        let GetSoftStakingProductListParams {
            asset,
            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) = 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::GetSoftStakingProductListResponse>(
            &self.configuration,
            "/sapi/v1/soft-staking/list",
            reqwest::Method::GET,
            query_params,
            body_params,
            if HAS_TIME_UNIT {
                self.configuration.time_unit
            } else {
                None
            },
            true,
        )
        .await
    }

    async fn get_soft_staking_rewards_history(
        &self,
        params: GetSoftStakingRewardsHistoryParams,
    ) -> anyhow::Result<RestApiResponse<models::GetSoftStakingRewardsHistoryResponse>> {
        let GetSoftStakingRewardsHistoryParams {
            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::GetSoftStakingRewardsHistoryResponse>(
            &self.configuration,
            "/sapi/v1/soft-staking/history/rewardsRecord",
            reqwest::Method::GET,
            query_params,
            body_params,
            if HAS_TIME_UNIT {
                self.configuration.time_unit
            } else {
                None
            },
            true,
        )
        .await
    }

    async fn set_soft_staking(
        &self,
        params: SetSoftStakingParams,
    ) -> anyhow::Result<RestApiResponse<models::SetSoftStakingResponse>> {
        let SetSoftStakingParams {
            soft_staking,
            recv_window,
        } = params;

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

        query_params.insert("softStaking".to_string(), json!(soft_staking));

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

        send_request::<models::SetSoftStakingResponse>(
            &self.configuration,
            "/sapi/v1/soft-staking/set",
            reqwest::Method::GET,
            query_params,
            body_params,
            if HAS_TIME_UNIT {
                self.configuration.time_unit
            } else {
                None
            },
            true,
        )
        .await
    }
}

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

    #[async_trait]
    impl SoftStakingApi for MockSoftStakingApiClient {
        async fn get_soft_staking_product_list(
            &self,
            _params: GetSoftStakingProductListParams,
        ) -> anyhow::Result<RestApiResponse<models::GetSoftStakingProductListResponse>> {
            if self.force_error {
                return Err(ConnectorError::ConnectorClientError {
                    msg: "ResponseError".to_string(),
                    code: None,
                }
                .into());
            }

            let resp_json: Value = serde_json::from_str(r#"{"status":true,"totalRewardsUsdt":"3.09827182","rows":[{"asset":"BNB","minAmount":"0.5","maxCap":"1000","apr":"0.0015","stakedAmount":"2.14","totalProfit":"0.00171234"},{"asset":"SUI","minAmount":"100","maxCap":"50000","apr":"0.01","stakedAmount":"100","totalProfit":"0.1"}],"total":2}"#).unwrap();
            let dummy_response: models::GetSoftStakingProductListResponse =
                serde_json::from_value(resp_json.clone())
                    .expect("should parse into models::GetSoftStakingProductListResponse");

            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_soft_staking_rewards_history(
            &self,
            _params: GetSoftStakingRewardsHistoryParams,
        ) -> anyhow::Result<RestApiResponse<models::GetSoftStakingRewardsHistoryResponse>> {
            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":[{"asset":"BNB","rewards":"0.00000557","rewardAsset":"BNB","avgAmount":"2.14","time":1754007978000},{"asset":"SUI","rewards":"0.00274257","rewardAsset":"SUI","avgAmount":"100","time":1754007978000}],"total":2}"#).unwrap();
            let dummy_response: models::GetSoftStakingRewardsHistoryResponse =
                serde_json::from_value(resp_json.clone())
                    .expect("should parse into models::GetSoftStakingRewardsHistoryResponse");

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

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

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

            let resp_json: Value = serde_json::from_str(r#"{"status":true,"totalRewardsUsdt":"3.09827182","rows":[{"asset":"BNB","minAmount":"0.5","maxCap":"1000","apr":"0.0015","stakedAmount":"2.14","totalProfit":"0.00171234"},{"asset":"SUI","minAmount":"100","maxCap":"50000","apr":"0.01","stakedAmount":"100","totalProfit":"0.1"}],"total":2}"#).unwrap();
            let expected_response : models::GetSoftStakingProductListResponse = serde_json::from_value(resp_json.clone()).expect("should parse into models::GetSoftStakingProductListResponse");

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

            let params = GetSoftStakingProductListParams::builder().asset("BETH".to_string()).current(1).size(10).recv_window(5000).build().unwrap();

            let resp_json: Value = serde_json::from_str(r#"{"status":true,"totalRewardsUsdt":"3.09827182","rows":[{"asset":"BNB","minAmount":"0.5","maxCap":"1000","apr":"0.0015","stakedAmount":"2.14","totalProfit":"0.00171234"},{"asset":"SUI","minAmount":"100","maxCap":"50000","apr":"0.01","stakedAmount":"100","totalProfit":"0.1"}],"total":2}"#).unwrap();
            let expected_response : models::GetSoftStakingProductListResponse = serde_json::from_value(resp_json.clone()).expect("should parse into models::GetSoftStakingProductListResponse");

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

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

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

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

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

            let resp_json: Value = serde_json::from_str(r#"{"rows":[{"asset":"BNB","rewards":"0.00000557","rewardAsset":"BNB","avgAmount":"2.14","time":1754007978000},{"asset":"SUI","rewards":"0.00274257","rewardAsset":"SUI","avgAmount":"100","time":1754007978000}],"total":2}"#).unwrap();
            let expected_response : models::GetSoftStakingRewardsHistoryResponse = serde_json::from_value(resp_json.clone()).expect("should parse into models::GetSoftStakingRewardsHistoryResponse");

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

            let params = GetSoftStakingRewardsHistoryParams::builder().asset("BETH".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":[{"asset":"BNB","rewards":"0.00000557","rewardAsset":"BNB","avgAmount":"2.14","time":1754007978000},{"asset":"SUI","rewards":"0.00274257","rewardAsset":"SUI","avgAmount":"100","time":1754007978000}],"total":2}"#).unwrap();
            let expected_response : models::GetSoftStakingRewardsHistoryResponse = serde_json::from_value(resp_json.clone()).expect("should parse into models::GetSoftStakingRewardsHistoryResponse");

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

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

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

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

            let params = SetSoftStakingParams::builder(true).build().unwrap();

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

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

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

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

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

            let params = SetSoftStakingParams::builder(true).build().unwrap();

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