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

const HAS_TIME_UNIT: bool = false;

#[async_trait]
pub trait FiatApi: Send + Sync {
    async fn deposit(
        &self,
        params: DepositParams,
    ) -> anyhow::Result<RestApiResponse<models::DepositResponse>>;
    async fn fiat_withdraw(
        &self,
        params: FiatWithdrawParams,
    ) -> anyhow::Result<RestApiResponse<models::FiatWithdrawResponse>>;
    async fn get_fiat_deposit_withdraw_history(
        &self,
        params: GetFiatDepositWithdrawHistoryParams,
    ) -> anyhow::Result<RestApiResponse<models::GetFiatDepositWithdrawHistoryResponse>>;
    async fn get_fiat_payments_history(
        &self,
        params: GetFiatPaymentsHistoryParams,
    ) -> anyhow::Result<RestApiResponse<models::GetFiatPaymentsHistoryResponse>>;
    async fn get_order_detail(
        &self,
        params: GetOrderDetailParams,
    ) -> anyhow::Result<RestApiResponse<models::GetOrderDetailResponse>>;
}

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

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

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

impl DepositParams {
    /// Create a builder for [`deposit`].
    ///
    /// Required parameters:
    ///
    /// * `currency` — String
    /// * `api_payment_method` — String
    /// * `amount` — i64
    ///
    #[must_use]
    pub fn builder(
        currency: String,
        api_payment_method: String,
        amount: i64,
    ) -> DepositParamsBuilder {
        DepositParamsBuilder::default()
            .currency(currency)
            .api_payment_method(api_payment_method)
            .amount(amount)
    }
}
/// Request parameters for the [`fiat_withdraw`] operation.
///
/// This struct holds all of the inputs you can pass when calling
/// [`fiat_withdraw`](#method.fiat_withdraw).
#[derive(Clone, Debug, Builder)]
#[builder(pattern = "owned", build_fn(error = "ParamBuildError"))]
pub struct FiatWithdrawParams {
    ///
    /// The `currency` parameter.
    ///
    /// This field is **required.
    #[builder(setter(into))]
    pub currency: String,
    ///
    /// The `api_payment_method` parameter.
    ///
    /// This field is **required.
    #[builder(setter(into))]
    pub api_payment_method: String,
    ///
    /// The `amount` parameter.
    ///
    /// This field is **required.
    #[builder(setter(into))]
    pub amount: i64,
    ///
    /// The `account_info` parameter.
    ///
    /// This field is **required.
    #[builder(setter(into))]
    pub account_info: models::AccountInfo,
    ///
    /// The `recv_window` parameter.
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub recv_window: Option<i64>,
    ///
    /// The `ext` parameter.
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub ext: Option<serde_json::Value>,
}

impl FiatWithdrawParams {
    /// Create a builder for [`fiat_withdraw`].
    ///
    /// Required parameters:
    ///
    /// * `currency` — String
    /// * `api_payment_method` — String
    /// * `amount` — i64
    /// * `account_info` — `models::AccountInfo`
    ///
    #[must_use]
    pub fn builder(
        currency: String,
        api_payment_method: String,
        amount: i64,
        account_info: models::AccountInfo,
    ) -> FiatWithdrawParamsBuilder {
        FiatWithdrawParamsBuilder::default()
            .currency(currency)
            .api_payment_method(api_payment_method)
            .amount(amount)
            .account_info(account_info)
    }
}
/// Request parameters for the [`get_fiat_deposit_withdraw_history`] operation.
///
/// This struct holds all of the inputs you can pass when calling
/// [`get_fiat_deposit_withdraw_history`](#method.get_fiat_deposit_withdraw_history).
#[derive(Clone, Debug, Builder)]
#[builder(pattern = "owned", build_fn(error = "ParamBuildError"))]
pub struct GetFiatDepositWithdrawHistoryParams {
    /// 0-buy,1-sell
    ///
    /// This field is **required.
    #[builder(setter(into))]
    pub transaction_type: String,
    ///
    /// The `begin_time` parameter.
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub begin_time: Option<i64>,
    ///
    /// The `end_time` parameter.
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub end_time: Option<i64>,
    /// default 1
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub page: Option<i64>,
    /// default 100, max 500
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub rows: Option<i64>,
    ///
    /// The `recv_window` parameter.
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub recv_window: Option<i64>,
}

impl GetFiatDepositWithdrawHistoryParams {
    /// Create a builder for [`get_fiat_deposit_withdraw_history`].
    ///
    /// Required parameters:
    ///
    /// * `transaction_type` — 0-buy,1-sell
    ///
    #[must_use]
    pub fn builder(transaction_type: String) -> GetFiatDepositWithdrawHistoryParamsBuilder {
        GetFiatDepositWithdrawHistoryParamsBuilder::default().transaction_type(transaction_type)
    }
}
/// Request parameters for the [`get_fiat_payments_history`] operation.
///
/// This struct holds all of the inputs you can pass when calling
/// [`get_fiat_payments_history`](#method.get_fiat_payments_history).
#[derive(Clone, Debug, Builder)]
#[builder(pattern = "owned", build_fn(error = "ParamBuildError"))]
pub struct GetFiatPaymentsHistoryParams {
    /// 0-buy,1-sell
    ///
    /// This field is **required.
    #[builder(setter(into))]
    pub transaction_type: String,
    ///
    /// The `begin_time` parameter.
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub begin_time: Option<i64>,
    ///
    /// The `end_time` parameter.
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub end_time: Option<i64>,
    /// default 1
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub page: Option<i64>,
    /// default 100, max 500
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub rows: Option<i64>,
    ///
    /// The `recv_window` parameter.
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub recv_window: Option<i64>,
}

impl GetFiatPaymentsHistoryParams {
    /// Create a builder for [`get_fiat_payments_history`].
    ///
    /// Required parameters:
    ///
    /// * `transaction_type` — 0-buy,1-sell
    ///
    #[must_use]
    pub fn builder(transaction_type: String) -> GetFiatPaymentsHistoryParamsBuilder {
        GetFiatPaymentsHistoryParamsBuilder::default().transaction_type(transaction_type)
    }
}
/// Request parameters for the [`get_order_detail`] operation.
///
/// This struct holds all of the inputs you can pass when calling
/// [`get_order_detail`](#method.get_order_detail).
#[derive(Clone, Debug, Builder)]
#[builder(pattern = "owned", build_fn(error = "ParamBuildError"))]
pub struct GetOrderDetailParams {
    /// order id retrieved from the api call of withdrawal
    ///
    /// This field is **required.
    #[builder(setter(into))]
    pub order_no: String,
    ///
    /// The `recv_window` parameter.
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub recv_window: Option<i64>,
}

impl GetOrderDetailParams {
    /// Create a builder for [`get_order_detail`].
    ///
    /// Required parameters:
    ///
    /// * `order_no` — order id retrieved from the api call of withdrawal
    ///
    #[must_use]
    pub fn builder(order_no: String) -> GetOrderDetailParamsBuilder {
        GetOrderDetailParamsBuilder::default().order_no(order_no)
    }
}

#[async_trait]
impl FiatApi for FiatApiClient {
    async fn deposit(
        &self,
        params: DepositParams,
    ) -> anyhow::Result<RestApiResponse<models::DepositResponse>> {
        let DepositParams {
            currency,
            api_payment_method,
            amount,
            recv_window,
            ext,
        } = params;

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

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

        body_params.insert("currency".to_string(), json!(currency));

        body_params.insert("apiPaymentMethod".to_string(), json!(api_payment_method));

        body_params.insert("amount".to_string(), json!(amount));

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

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

    async fn fiat_withdraw(
        &self,
        params: FiatWithdrawParams,
    ) -> anyhow::Result<RestApiResponse<models::FiatWithdrawResponse>> {
        let FiatWithdrawParams {
            currency,
            api_payment_method,
            amount,
            account_info,
            recv_window,
            ext,
        } = params;

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

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

        body_params.insert("currency".to_string(), json!(currency));

        body_params.insert("apiPaymentMethod".to_string(), json!(api_payment_method));

        body_params.insert("amount".to_string(), json!(amount));

        body_params.insert("accountInfo".to_string(), json!(account_info));

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

        send_request::<models::FiatWithdrawResponse>(
            &self.configuration,
            "/sapi/v2/fiat/withdraw",
            reqwest::Method::POST,
            query_params,
            body_params,
            if HAS_TIME_UNIT {
                self.configuration.time_unit
            } else {
                None
            },
            true,
        )
        .await
    }

    async fn get_fiat_deposit_withdraw_history(
        &self,
        params: GetFiatDepositWithdrawHistoryParams,
    ) -> anyhow::Result<RestApiResponse<models::GetFiatDepositWithdrawHistoryResponse>> {
        let GetFiatDepositWithdrawHistoryParams {
            transaction_type,
            begin_time,
            end_time,
            page,
            rows,
            recv_window,
        } = params;

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

        query_params.insert("transactionType".to_string(), json!(transaction_type));

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

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

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

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

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

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

    async fn get_fiat_payments_history(
        &self,
        params: GetFiatPaymentsHistoryParams,
    ) -> anyhow::Result<RestApiResponse<models::GetFiatPaymentsHistoryResponse>> {
        let GetFiatPaymentsHistoryParams {
            transaction_type,
            begin_time,
            end_time,
            page,
            rows,
            recv_window,
        } = params;

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

        query_params.insert("transactionType".to_string(), json!(transaction_type));

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

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

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

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

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

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

    async fn get_order_detail(
        &self,
        params: GetOrderDetailParams,
    ) -> anyhow::Result<RestApiResponse<models::GetOrderDetailResponse>> {
        let GetOrderDetailParams {
            order_no,
            recv_window,
        } = params;

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

        query_params.insert("orderNo".to_string(), json!(order_no));

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

        send_request::<models::GetOrderDetailResponse>(
            &self.configuration,
            "/sapi/v1/fiat/get-order-detail",
            reqwest::Method::GET,
            query_params,
            body_params,
            if HAS_TIME_UNIT {
                self.configuration.time_unit
            } else {
                None
            },
            true,
        )
        .await
    }
}

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

    #[async_trait]
    impl FiatApi for MockFiatApiClient {
        async fn deposit(
            &self,
            _params: DepositParams,
        ) -> anyhow::Result<RestApiResponse<models::DepositResponse>> {
            if self.force_error {
                return Err(ConnectorError::ConnectorClientError {
                    msg: "ResponseError".to_string(),
                    code: None,
                }
                .into());
            }

            let resp_json: Value = serde_json::from_str(
                r#"{"code":"000000","message":"success","data":{"orderId":"04595xxxxxxxxx37"}}"#,
            )
            .unwrap();
            let dummy_response: models::DepositResponse = serde_json::from_value(resp_json.clone())
                .expect("should parse into models::DepositResponse");

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

            let resp_json: Value = serde_json::from_str(
                r#"{"code":"000000","message":"success","data":{"orderId":"04595xxxxxxxxx37"}}"#,
            )
            .unwrap();
            let dummy_response: models::FiatWithdrawResponse =
                serde_json::from_value(resp_json.clone())
                    .expect("should parse into models::FiatWithdrawResponse");

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

            let resp_json: Value = serde_json::from_str(r#"{"code":"000000","message":"success","data":[{"orderNo":"7d76d611-0568-4f43-afb6-24cac7767365","fiatCurrency":"BRL","indicatedAmount":"10.00","amount":"10.00","totalFee":"0.00","method":"BankAccount","status":"Expired","createTime":1626144956000,"updateTime":1626400907000}],"total":1,"success":true}"#).unwrap();
            let dummy_response: models::GetFiatDepositWithdrawHistoryResponse =
                serde_json::from_value(resp_json.clone())
                    .expect("should parse into models::GetFiatDepositWithdrawHistoryResponse");

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

            let resp_json: Value = serde_json::from_str(r#"{"code":"000000","message":"success","data":[{"orderNo":"353fca443f06466db0c4dc89f94f027a","sourceAmount":"20.0","fiatCurrency":"EUR","obtainAmount":"4.462","cryptoCurrency":"LUNA","totalFee":"0.2","price":"4.437472","status":"Failed","paymentMethod":"Credit Card","createTime":1624529919000,"updateTime":1624529919000}],"total":1,"success":true}"#).unwrap();
            let dummy_response: models::GetFiatPaymentsHistoryResponse =
                serde_json::from_value(resp_json.clone())
                    .expect("should parse into models::GetFiatPaymentsHistoryResponse");

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

            let resp_json: Value = serde_json::from_str(r#"{"code":"000000","message":"success","data":{"orderId":"036752*678","orderStatus":"ORDER_INITIAL","amount":"4.33","fee":"0.43","fiatCurrency":"***","errorCode":"","errorMessage":"","ext":{}}}"#).unwrap();
            let dummy_response: models::GetOrderDetailResponse =
                serde_json::from_value(resp_json.clone())
                    .expect("should parse into models::GetOrderDetailResponse");

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

            let params = DepositParams::builder(
                "currency_example".to_string(),
                "api_payment_method_example".to_string(),
                789,
            )
            .build()
            .unwrap();

            let resp_json: Value = serde_json::from_str(
                r#"{"code":"000000","message":"success","data":{"orderId":"04595xxxxxxxxx37"}}"#,
            )
            .unwrap();
            let expected_response: models::DepositResponse =
                serde_json::from_value(resp_json.clone())
                    .expect("should parse into models::DepositResponse");

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

            let params = DepositParams::builder(
                "currency_example".to_string(),
                "api_payment_method_example".to_string(),
                789,
            )
            .recv_window(5000)
            .ext(serde_json::Value::Object(Default::default()))
            .build()
            .unwrap();

            let resp_json: Value = serde_json::from_str(
                r#"{"code":"000000","message":"success","data":{"orderId":"04595xxxxxxxxx37"}}"#,
            )
            .unwrap();
            let expected_response: models::DepositResponse =
                serde_json::from_value(resp_json.clone())
                    .expect("should parse into models::DepositResponse");

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

            let params = DepositParams::builder(
                "currency_example".to_string(),
                "api_payment_method_example".to_string(),
                789,
            )
            .build()
            .unwrap();

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

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

            let params = FiatWithdrawParams::builder(
                "currency_example".to_string(),
                "api_payment_method_example".to_string(),
                789,
                models::AccountInfo::new(),
            )
            .build()
            .unwrap();

            let resp_json: Value = serde_json::from_str(
                r#"{"code":"000000","message":"success","data":{"orderId":"04595xxxxxxxxx37"}}"#,
            )
            .unwrap();
            let expected_response: models::FiatWithdrawResponse =
                serde_json::from_value(resp_json.clone())
                    .expect("should parse into models::FiatWithdrawResponse");

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

            let params = FiatWithdrawParams::builder(
                "currency_example".to_string(),
                "api_payment_method_example".to_string(),
                789,
                models::AccountInfo::new(),
            )
            .recv_window(5000)
            .ext(serde_json::Value::Object(Default::default()))
            .build()
            .unwrap();

            let resp_json: Value = serde_json::from_str(
                r#"{"code":"000000","message":"success","data":{"orderId":"04595xxxxxxxxx37"}}"#,
            )
            .unwrap();
            let expected_response: models::FiatWithdrawResponse =
                serde_json::from_value(resp_json.clone())
                    .expect("should parse into models::FiatWithdrawResponse");

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

            let params = FiatWithdrawParams::builder(
                "currency_example".to_string(),
                "api_payment_method_example".to_string(),
                789,
                models::AccountInfo::new(),
            )
            .build()
            .unwrap();

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

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

            let params = GetFiatDepositWithdrawHistoryParams::builder("transaction_type_example".to_string(),).build().unwrap();

            let resp_json: Value = serde_json::from_str(r#"{"code":"000000","message":"success","data":[{"orderNo":"7d76d611-0568-4f43-afb6-24cac7767365","fiatCurrency":"BRL","indicatedAmount":"10.00","amount":"10.00","totalFee":"0.00","method":"BankAccount","status":"Expired","createTime":1626144956000,"updateTime":1626400907000}],"total":1,"success":true}"#).unwrap();
            let expected_response : models::GetFiatDepositWithdrawHistoryResponse = serde_json::from_value(resp_json.clone()).expect("should parse into models::GetFiatDepositWithdrawHistoryResponse");

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

            let params = GetFiatDepositWithdrawHistoryParams::builder("transaction_type_example".to_string(),).begin_time(789).end_time(1641782889000).page(1).rows(100).recv_window(5000).build().unwrap();

            let resp_json: Value = serde_json::from_str(r#"{"code":"000000","message":"success","data":[{"orderNo":"7d76d611-0568-4f43-afb6-24cac7767365","fiatCurrency":"BRL","indicatedAmount":"10.00","amount":"10.00","totalFee":"0.00","method":"BankAccount","status":"Expired","createTime":1626144956000,"updateTime":1626400907000}],"total":1,"success":true}"#).unwrap();
            let expected_response : models::GetFiatDepositWithdrawHistoryResponse = serde_json::from_value(resp_json.clone()).expect("should parse into models::GetFiatDepositWithdrawHistoryResponse");

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

            let params = GetFiatDepositWithdrawHistoryParams::builder(
                "transaction_type_example".to_string(),
            )
            .build()
            .unwrap();

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

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

            let params = GetFiatPaymentsHistoryParams::builder("transaction_type_example".to_string(),).build().unwrap();

            let resp_json: Value = serde_json::from_str(r#"{"code":"000000","message":"success","data":[{"orderNo":"353fca443f06466db0c4dc89f94f027a","sourceAmount":"20.0","fiatCurrency":"EUR","obtainAmount":"4.462","cryptoCurrency":"LUNA","totalFee":"0.2","price":"4.437472","status":"Failed","paymentMethod":"Credit Card","createTime":1624529919000,"updateTime":1624529919000}],"total":1,"success":true}"#).unwrap();
            let expected_response : models::GetFiatPaymentsHistoryResponse = serde_json::from_value(resp_json.clone()).expect("should parse into models::GetFiatPaymentsHistoryResponse");

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

            let params = GetFiatPaymentsHistoryParams::builder("transaction_type_example".to_string(),).begin_time(789).end_time(1641782889000).page(1).rows(100).recv_window(5000).build().unwrap();

            let resp_json: Value = serde_json::from_str(r#"{"code":"000000","message":"success","data":[{"orderNo":"353fca443f06466db0c4dc89f94f027a","sourceAmount":"20.0","fiatCurrency":"EUR","obtainAmount":"4.462","cryptoCurrency":"LUNA","totalFee":"0.2","price":"4.437472","status":"Failed","paymentMethod":"Credit Card","createTime":1624529919000,"updateTime":1624529919000}],"total":1,"success":true}"#).unwrap();
            let expected_response : models::GetFiatPaymentsHistoryResponse = serde_json::from_value(resp_json.clone()).expect("should parse into models::GetFiatPaymentsHistoryResponse");

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

            let params =
                GetFiatPaymentsHistoryParams::builder("transaction_type_example".to_string())
                    .build()
                    .unwrap();

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

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

            let params = GetOrderDetailParams::builder("order_no_example".to_string(),).build().unwrap();

            let resp_json: Value = serde_json::from_str(r#"{"code":"000000","message":"success","data":{"orderId":"036752*678","orderStatus":"ORDER_INITIAL","amount":"4.33","fee":"0.43","fiatCurrency":"***","errorCode":"","errorMessage":"","ext":{}}}"#).unwrap();
            let expected_response : models::GetOrderDetailResponse = serde_json::from_value(resp_json.clone()).expect("should parse into models::GetOrderDetailResponse");

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

            let params = GetOrderDetailParams::builder("order_no_example".to_string(),).recv_window(5000).build().unwrap();

            let resp_json: Value = serde_json::from_str(r#"{"code":"000000","message":"success","data":{"orderId":"036752*678","orderStatus":"ORDER_INITIAL","amount":"4.33","fee":"0.43","fiatCurrency":"***","errorCode":"","errorMessage":"","ext":{}}}"#).unwrap();
            let expected_response : models::GetOrderDetailResponse = serde_json::from_value(resp_json.clone()).expect("should parse into models::GetOrderDetailResponse");

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

            let params = GetOrderDetailParams::builder("order_no_example".to_string())
                .build()
                .unwrap();

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