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

const HAS_TIME_UNIT: bool = false;

#[async_trait]
pub trait OthersApi: Send + Sync {
    async fn get_symbols_delist_schedule_for_spot(
        &self,
        params: GetSymbolsDelistScheduleForSpotParams,
    ) -> anyhow::Result<RestApiResponse<Vec<models::GetSymbolsDelistScheduleForSpotResponseInner>>>;
    async fn system_status(&self) -> anyhow::Result<RestApiResponse<models::SystemStatusResponse>>;
}

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

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

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

impl GetSymbolsDelistScheduleForSpotParams {
    /// Create a builder for [`get_symbols_delist_schedule_for_spot`].
    ///
    #[must_use]
    pub fn builder() -> GetSymbolsDelistScheduleForSpotParamsBuilder {
        GetSymbolsDelistScheduleForSpotParamsBuilder::default()
    }
}

#[async_trait]
impl OthersApi for OthersApiClient {
    async fn get_symbols_delist_schedule_for_spot(
        &self,
        params: GetSymbolsDelistScheduleForSpotParams,
    ) -> anyhow::Result<RestApiResponse<Vec<models::GetSymbolsDelistScheduleForSpotResponseInner>>>
    {
        let GetSymbolsDelistScheduleForSpotParams { 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::GetSymbolsDelistScheduleForSpotResponseInner>>(
            &self.configuration,
            "/sapi/v1/spot/delist-schedule",
            reqwest::Method::GET,
            query_params,
            body_params,
            if HAS_TIME_UNIT {
                self.configuration.time_unit
            } else {
                None
            },
            false,
        )
        .await
    }

    async fn system_status(&self) -> anyhow::Result<RestApiResponse<models::SystemStatusResponse>> {
        let query_params = BTreeMap::new();
        let body_params = BTreeMap::new();

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

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

    #[async_trait]
    impl OthersApi for MockOthersApiClient {
        async fn get_symbols_delist_schedule_for_spot(
            &self,
            _params: GetSymbolsDelistScheduleForSpotParams,
        ) -> anyhow::Result<
            RestApiResponse<Vec<models::GetSymbolsDelistScheduleForSpotResponseInner>>,
        > {
            if self.force_error {
                return Err(
                    ConnectorError::ConnectorClientError("ResponseError".to_string()).into(),
                );
            }

            let resp_json: Value = serde_json::from_str(r#"[{"delistTime":1686161202000,"symbols":["ADAUSDT","BNBUSDT"]},{"delistTime":1686222232000,"symbols":["ETHUSDT"]}]"#).unwrap();
            let dummy_response: Vec<models::GetSymbolsDelistScheduleForSpotResponseInner> =
                serde_json::from_value(resp_json.clone()).expect(
                    "should parse into Vec<models::GetSymbolsDelistScheduleForSpotResponseInner>",
                );

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

            let resp_json: Value = serde_json::from_str(r#"{"status":0,"msg":"normal"}"#).unwrap();
            let dummy_response: models::SystemStatusResponse =
                serde_json::from_value(resp_json.clone())
                    .expect("should parse into models::SystemStatusResponse");

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

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

            let resp_json: Value = serde_json::from_str(r#"[{"delistTime":1686161202000,"symbols":["ADAUSDT","BNBUSDT"]},{"delistTime":1686222232000,"symbols":["ETHUSDT"]}]"#).unwrap();
            let expected_response : Vec<models::GetSymbolsDelistScheduleForSpotResponseInner> = serde_json::from_value(resp_json.clone()).expect("should parse into Vec<models::GetSymbolsDelistScheduleForSpotResponseInner>");

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

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

            let resp_json: Value = serde_json::from_str(r#"[{"delistTime":1686161202000,"symbols":["ADAUSDT","BNBUSDT"]},{"delistTime":1686222232000,"symbols":["ETHUSDT"]}]"#).unwrap();
            let expected_response : Vec<models::GetSymbolsDelistScheduleForSpotResponseInner> = serde_json::from_value(resp_json.clone()).expect("should parse into Vec<models::GetSymbolsDelistScheduleForSpotResponseInner>");

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

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

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

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

            let resp_json: Value = serde_json::from_str(r#"{"status":0,"msg":"normal"}"#).unwrap();
            let expected_response: models::SystemStatusResponse =
                serde_json::from_value(resp_json.clone())
                    .expect("should parse into models::SystemStatusResponse");

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

            let resp_json: Value = serde_json::from_str(r#"{"status":0,"msg":"normal"}"#).unwrap();
            let expected_response: models::SystemStatusResponse =
                serde_json::from_value(resp_json.clone())
                    .expect("should parse into models::SystemStatusResponse");

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

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