/*
 * Prediction Trading REST API
 *
 * Place and manage prediction market orders, query positions, and transfer funds via the Prediction Trading 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::w3w_prediction::rest_api::models;

const HAS_TIME_UNIT: bool = false;

#[async_trait]
pub trait MarketDataApi: Send + Sync {
    async fn get_market_detail(
        &self,
        params: GetMarketDetailParams,
    ) -> anyhow::Result<RestApiResponse<models::GetMarketDetailResponse>>;
    async fn list_prediction_categories(
        &self,
    ) -> anyhow::Result<RestApiResponse<models::ListPredictionCategoriesResponse>>;
    async fn list_prediction_markets(
        &self,
        params: ListPredictionMarketsParams,
    ) -> anyhow::Result<RestApiResponse<models::ListPredictionMarketsResponse>>;
    async fn market_search(
        &self,
        params: MarketSearchParams,
    ) -> anyhow::Result<RestApiResponse<Vec<models::MarketSearchResponseInner>>>;
    async fn query_last_trade_price(
        &self,
        params: QueryLastTradePriceParams,
    ) -> anyhow::Result<RestApiResponse<models::QueryLastTradePriceResponse>>;
    async fn query_order_book(
        &self,
        params: QueryOrderBookParams,
    ) -> anyhow::Result<RestApiResponse<models::QueryOrderBookResponse>>;
}

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

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

#[allow(non_camel_case_types)]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum ListPredictionMarketsSortByEnum {
    #[serde(rename = "RECOMMENDED")]
    Recommended,
    #[serde(rename = "VOLUME")]
    Volume,
    #[serde(rename = "PARTICIPANTS")]
    Participants,
    #[serde(rename = "CREATED_TIME")]
    CreatedTime,
    #[serde(rename = "END_DATE")]
    EndDate,
}

impl ListPredictionMarketsSortByEnum {
    #[must_use]
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::Recommended => "RECOMMENDED",
            Self::Volume => "VOLUME",
            Self::Participants => "PARTICIPANTS",
            Self::CreatedTime => "CREATED_TIME",
            Self::EndDate => "END_DATE",
        }
    }
}

impl std::str::FromStr for ListPredictionMarketsSortByEnum {
    type Err = Box<dyn std::error::Error + Send + Sync>;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "RECOMMENDED" => Ok(Self::Recommended),
            "VOLUME" => Ok(Self::Volume),
            "PARTICIPANTS" => Ok(Self::Participants),
            "CREATED_TIME" => Ok(Self::CreatedTime),
            "END_DATE" => Ok(Self::EndDate),
            other => Err(format!("invalid ListPredictionMarketsSortByEnum: {}", other).into()),
        }
    }
}

#[allow(non_camel_case_types)]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum ListPredictionMarketsOrderByEnum {
    #[serde(rename = "ASC")]
    Asc,
    #[serde(rename = "DESC")]
    Desc,
}

impl ListPredictionMarketsOrderByEnum {
    #[must_use]
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::Asc => "ASC",
            Self::Desc => "DESC",
        }
    }
}

impl std::str::FromStr for ListPredictionMarketsOrderByEnum {
    type Err = Box<dyn std::error::Error + Send + Sync>;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "ASC" => Ok(Self::Asc),
            "DESC" => Ok(Self::Desc),
            other => Err(format!("invalid ListPredictionMarketsOrderByEnum: {}", other).into()),
        }
    }
}

/// Request parameters for the [`get_market_detail`] operation.
///
/// This struct holds all of the inputs you can pass when calling
/// [`get_market_detail`](#method.get_market_detail).
#[derive(Clone, Debug, Builder)]
#[builder(pattern = "owned", build_fn(error = "ParamBuildError"))]
pub struct GetMarketDetailParams {
    /// Market topic ID. Must be > 0
    ///
    /// This field is **required.
    #[builder(setter(into))]
    pub market_topic_id: i64,
}

impl GetMarketDetailParams {
    /// Create a builder for [`get_market_detail`].
    ///
    /// Required parameters:
    ///
    /// * `market_topic_id` — Market topic ID. Must be > 0
    ///
    #[must_use]
    pub fn builder(market_topic_id: i64) -> GetMarketDetailParamsBuilder {
        GetMarketDetailParamsBuilder::default().market_topic_id(market_topic_id)
    }
}
/// Request parameters for the [`list_prediction_markets`] operation.
///
/// This struct holds all of the inputs you can pass when calling
/// [`list_prediction_markets`](#method.list_prediction_markets).
#[derive(Clone, Debug, Builder, Default)]
#[builder(pattern = "owned", build_fn(error = "ParamBuildError"))]
pub struct ListPredictionMarketsParams {
    /// Level-1 category filter
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub l1_category: Option<String>,
    /// Level-2 category filter
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub l2_category: Option<String>,
    /// Sort field. Enum: `RECOMMENDED`, `VOLUME`, `PARTICIPANTS`, `CREATED_TIME`, `END_DATE`
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub sort_by: Option<ListPredictionMarketsSortByEnum>,
    /// Sort direction. Enum: `ASC`, `DESC`
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub order_by: Option<ListPredictionMarketsOrderByEnum>,
    /// Pagination offset. Default `0`
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub offset: Option<i32>,
    /// Page size. Default `20`, range 1–100
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub limit: Option<i32>,
}

impl ListPredictionMarketsParams {
    /// Create a builder for [`list_prediction_markets`].
    ///
    #[must_use]
    pub fn builder() -> ListPredictionMarketsParamsBuilder {
        ListPredictionMarketsParamsBuilder::default()
    }
}
/// Request parameters for the [`market_search`] operation.
///
/// This struct holds all of the inputs you can pass when calling
/// [`market_search`](#method.market_search).
#[derive(Clone, Debug, Builder)]
#[builder(pattern = "owned", build_fn(error = "ParamBuildError"))]
pub struct MarketSearchParams {
    /// Search keyword. Not blank
    ///
    /// This field is **required.
    #[builder(setter(into))]
    pub query: String,
    /// Max number of results to return. Default `20`, range 1–50
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub top_k: Option<i32>,
}

impl MarketSearchParams {
    /// Create a builder for [`market_search`].
    ///
    /// Required parameters:
    ///
    /// * `query` — Search keyword. Not blank
    ///
    #[must_use]
    pub fn builder(query: String) -> MarketSearchParamsBuilder {
        MarketSearchParamsBuilder::default().query(query)
    }
}
/// Request parameters for the [`query_last_trade_price`] operation.
///
/// This struct holds all of the inputs you can pass when calling
/// [`query_last_trade_price`](#method.query_last_trade_price).
#[derive(Clone, Debug, Builder)]
#[builder(pattern = "owned", build_fn(error = "ParamBuildError"))]
pub struct QueryLastTradePriceParams {
    /// Market ID. Must be > 0
    ///
    /// This field is **required.
    #[builder(setter(into))]
    pub market_id: i64,
}

impl QueryLastTradePriceParams {
    /// Create a builder for [`query_last_trade_price`].
    ///
    /// Required parameters:
    ///
    /// * `market_id` — Market ID. Must be > 0
    ///
    #[must_use]
    pub fn builder(market_id: i64) -> QueryLastTradePriceParamsBuilder {
        QueryLastTradePriceParamsBuilder::default().market_id(market_id)
    }
}
/// Request parameters for the [`query_order_book`] operation.
///
/// This struct holds all of the inputs you can pass when calling
/// [`query_order_book`](#method.query_order_book).
#[derive(Clone, Debug, Builder)]
#[builder(pattern = "owned", build_fn(error = "ParamBuildError"))]
pub struct QueryOrderBookParams {
    /// Vendor identifier (e.g. `predict_fun`)
    ///
    /// This field is **required.
    #[builder(setter(into))]
    pub vendor: String,
    /// Market ID. Must be > 0
    ///
    /// This field is **required.
    #[builder(setter(into))]
    pub market_id: i64,
    /// Prediction outcome token ID
    ///
    /// This field is **required.
    #[builder(setter(into))]
    pub token_id: String,
}

impl QueryOrderBookParams {
    /// Create a builder for [`query_order_book`].
    ///
    /// Required parameters:
    ///
    /// * `vendor` — Vendor identifier (e.g. `predict_fun`)
    /// * `market_id` — Market ID. Must be > 0
    /// * `token_id` — Prediction outcome token ID
    ///
    #[must_use]
    pub fn builder(
        vendor: String,
        market_id: i64,
        token_id: String,
    ) -> QueryOrderBookParamsBuilder {
        QueryOrderBookParamsBuilder::default()
            .vendor(vendor)
            .market_id(market_id)
            .token_id(token_id)
    }
}

#[async_trait]
impl MarketDataApi for MarketDataApiClient {
    async fn get_market_detail(
        &self,
        params: GetMarketDetailParams,
    ) -> anyhow::Result<RestApiResponse<models::GetMarketDetailResponse>> {
        let GetMarketDetailParams { market_topic_id } = params;

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

        query_params.insert("marketTopicId".to_string(), json!(market_topic_id));

        send_request::<models::GetMarketDetailResponse>(
            &self.configuration,
            "/sapi/v1/w3w/wallet/prediction/market/detail",
            reqwest::Method::GET,
            query_params,
            body_params,
            if HAS_TIME_UNIT {
                self.configuration.time_unit
            } else {
                None
            },
            true,
        )
        .await
    }

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

        send_request::<models::ListPredictionCategoriesResponse>(
            &self.configuration,
            "/sapi/v1/w3w/wallet/prediction/category/list",
            reqwest::Method::GET,
            query_params,
            body_params,
            if HAS_TIME_UNIT {
                self.configuration.time_unit
            } else {
                None
            },
            true,
        )
        .await
    }

    async fn list_prediction_markets(
        &self,
        params: ListPredictionMarketsParams,
    ) -> anyhow::Result<RestApiResponse<models::ListPredictionMarketsResponse>> {
        let ListPredictionMarketsParams {
            l1_category,
            l2_category,
            sort_by,
            order_by,
            offset,
            limit,
        } = params;

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

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

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

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

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

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

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

        send_request::<models::ListPredictionMarketsResponse>(
            &self.configuration,
            "/sapi/v1/w3w/wallet/prediction/market/list",
            reqwest::Method::GET,
            query_params,
            body_params,
            if HAS_TIME_UNIT {
                self.configuration.time_unit
            } else {
                None
            },
            true,
        )
        .await
    }

    async fn market_search(
        &self,
        params: MarketSearchParams,
    ) -> anyhow::Result<RestApiResponse<Vec<models::MarketSearchResponseInner>>> {
        let MarketSearchParams { query, top_k } = params;

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

        query_params.insert("query".to_string(), json!(query));

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

        send_request::<Vec<models::MarketSearchResponseInner>>(
            &self.configuration,
            "/sapi/v1/w3w/wallet/prediction/market/search",
            reqwest::Method::GET,
            query_params,
            body_params,
            if HAS_TIME_UNIT {
                self.configuration.time_unit
            } else {
                None
            },
            true,
        )
        .await
    }

    async fn query_last_trade_price(
        &self,
        params: QueryLastTradePriceParams,
    ) -> anyhow::Result<RestApiResponse<models::QueryLastTradePriceResponse>> {
        let QueryLastTradePriceParams { market_id } = params;

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

        query_params.insert("marketId".to_string(), json!(market_id));

        send_request::<models::QueryLastTradePriceResponse>(
            &self.configuration,
            "/sapi/v1/w3w/wallet/prediction/order-book/last-trade-price",
            reqwest::Method::GET,
            query_params,
            body_params,
            if HAS_TIME_UNIT {
                self.configuration.time_unit
            } else {
                None
            },
            true,
        )
        .await
    }

    async fn query_order_book(
        &self,
        params: QueryOrderBookParams,
    ) -> anyhow::Result<RestApiResponse<models::QueryOrderBookResponse>> {
        let QueryOrderBookParams {
            vendor,
            market_id,
            token_id,
        } = params;

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

        query_params.insert("vendor".to_string(), json!(vendor));

        query_params.insert("marketId".to_string(), json!(market_id));

        query_params.insert("tokenId".to_string(), json!(token_id));

        send_request::<models::QueryOrderBookResponse>(
            &self.configuration,
            "/sapi/v1/w3w/wallet/prediction/order-book",
            reqwest::Method::GET,
            query_params,
            body_params,
            if HAS_TIME_UNIT {
                self.configuration.time_unit
            } else {
                None
            },
            true,
        )
        .await
    }
}

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

            let resp_json: Value = serde_json::from_str(r#"{"marketTopicId":4229564,"vendor":"PREDICT_FUN","chainId":"56","slug":"btc-price-1h-up-or-down","title":"BTC Price 1h Up or Down?","question":"Will BTC price go UP in the next 1 hour?","description":"Resolves YES if BTC spot price is higher than the starting price at resolution time.","imageUrl":"https://cdn.example.com/prediction/btc-1h.png","topicType":"FLAT","chartType":"CRYPTO_UP_DOWN","symbol":"BTCUSDT","variantData":{"type":"CRYPTO_UP_DOWN","startPrice":"67890.12","endPrice":"endPrice","priceFeedId":"0xpricefeedid123","priceFeedProvider":"BINANCE","priceFeedSymbol":"BTCUSDT"},"participantCount":3420,"collateral":"USDT","feeRateBps":200,"slippageBps":1200,"isYieldBearing":false,"tradeVolume":"158234.56","liquidity":"45000.00","publishedAt":1748100000000,"startDate":1748131200000,"endDate":1748134800000,"status":"REGISTERED","timeline":[{"marketTopicId":4229560,"startDate":1748127600000,"endDate":1748131200000}],"markets":[{"marketId":5567895,"externalId":"ext_001","title":"UP","question":"Will BTC go UP?","description":"Resolves YES if BTC price increases.","conditionId":"0xabc123","status":"REGISTERED","tradingStatus":"OPEN","tradeVolume":"90000.00","liquidity":"25000.00","decimalPrecision":2,"outcomes":[{"name":"YES","price":"0.52","chance":"0.52","index":0,"tokenId":"112233"}]}]}"#).unwrap_or_else(|_| serde_json::json!({}));
            let dummy_response: models::GetMarketDetailResponse =
                serde_json::from_value(resp_json.clone())
                    .expect("should parse into models::GetMarketDetailResponse");

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

            let resp_json: Value = serde_json::from_str(r#"{"categories":[{"id":"crypto","name":"Crypto","icon":"crypto_icon","order":1,"subcategories":[{"id":"up-down","name":"Up/Down","icon":"updown_icon","order":1}]}]}"#).unwrap_or_else(|_| serde_json::json!({}));
            let dummy_response: models::ListPredictionCategoriesResponse =
                serde_json::from_value(resp_json.clone())
                    .expect("should parse into models::ListPredictionCategoriesResponse");

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

            let resp_json: Value = serde_json::from_str(r#"{"marketTopics":[{"marketTopicId":4229564,"vendor":"PREDICT_FUN","chainId":"56","slug":"btc-price-1h-up-or-down","title":"BTC Price 1h Up or Down?","question":"Will BTC price go UP in the next 1 hour?","description":"Resolves YES if BTC spot price is higher than the starting price at resolution time.","imageUrl":"https://cdn.example.com/prediction/btc-1h.png","topicType":"FLAT","chartType":"CRYPTO_UP_DOWN","symbol":"BTCUSDT","participantCount":3420,"collateral":"USDT","feeRateBps":200,"slippageBps":1200,"isYieldBearing":false,"tradeVolume":"158234.56","liquidity":"45000.00","publishedAt":1748100000000,"startDate":1748131200000,"endDate":1748134800000,"status":"REGISTERED","markets":[{}]}],"total":128,"offset":0,"limit":20,"hasMore":true}"#).unwrap_or_else(|_| serde_json::json!({}));
            let dummy_response: models::ListPredictionMarketsResponse =
                serde_json::from_value(resp_json.clone())
                    .expect("should parse into models::ListPredictionMarketsResponse");

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

            let resp_json: Value = serde_json::from_str(r#"[{"marketTopicId":4229564,"vendor":"PREDICT_FUN","chainId":"56","slug":"btc-price-1h-up-or-down","title":"BTC Price 1h Up or Down?","question":"Will BTC price go UP in the next 1 hour?","description":"Resolves YES if BTC spot price is higher than the starting price.","topicType":"FLAT","chartType":"CRYPTO_UP_DOWN","symbol":"BTCUSDT","participantCount":3420,"collateral":"USDT","tradeVolume":"158234.56","liquidity":"45000.00","startDate":1748131200000,"endDate":1748134800000,"status":"REGISTERED","markets":[{}]}]"#).unwrap_or_else(|_| serde_json::json!({}));
            let dummy_response: Vec<models::MarketSearchResponseInner> =
                serde_json::from_value(resp_json.clone())
                    .expect("should parse into Vec<models::MarketSearchResponseInner>");

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

            let resp_json: Value =
                serde_json::from_str(r#"{"marketId":5567895,"lastTradePrice":"0.52"}"#)
                    .unwrap_or_else(|_| serde_json::json!({}));
            let dummy_response: models::QueryLastTradePriceResponse =
                serde_json::from_value(resp_json.clone())
                    .expect("should parse into models::QueryLastTradePriceResponse");

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

            let resp_json: Value = serde_json::from_str(r#"{"outcome":"YES","tokenId":"112233","timestamp":1748131800000,"bids":[{"price":"0.51","size":"5000.00"}],"asks":[{"price":"0.52","size":"3000.00"}]}"#).unwrap_or_else(|_| serde_json::json!({}));
            let dummy_response: models::QueryOrderBookResponse =
                serde_json::from_value(resp_json.clone())
                    .expect("should parse into models::QueryOrderBookResponse");

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

            let params = GetMarketDetailParams::builder(4229564).build().unwrap();

            let resp_json: Value = serde_json::from_str(r#"{"marketTopicId":4229564,"vendor":"PREDICT_FUN","chainId":"56","slug":"btc-price-1h-up-or-down","title":"BTC Price 1h Up or Down?","question":"Will BTC price go UP in the next 1 hour?","description":"Resolves YES if BTC spot price is higher than the starting price at resolution time.","imageUrl":"https://cdn.example.com/prediction/btc-1h.png","topicType":"FLAT","chartType":"CRYPTO_UP_DOWN","symbol":"BTCUSDT","variantData":{"type":"CRYPTO_UP_DOWN","startPrice":"67890.12","endPrice":"endPrice","priceFeedId":"0xpricefeedid123","priceFeedProvider":"BINANCE","priceFeedSymbol":"BTCUSDT"},"participantCount":3420,"collateral":"USDT","feeRateBps":200,"slippageBps":1200,"isYieldBearing":false,"tradeVolume":"158234.56","liquidity":"45000.00","publishedAt":1748100000000,"startDate":1748131200000,"endDate":1748134800000,"status":"REGISTERED","timeline":[{"marketTopicId":4229560,"startDate":1748127600000,"endDate":1748131200000}],"markets":[{"marketId":5567895,"externalId":"ext_001","title":"UP","question":"Will BTC go UP?","description":"Resolves YES if BTC price increases.","conditionId":"0xabc123","status":"REGISTERED","tradingStatus":"OPEN","tradeVolume":"90000.00","liquidity":"25000.00","decimalPrecision":2,"outcomes":[{"name":"YES","price":"0.52","chance":"0.52","index":0,"tokenId":"112233"}]}]}"#).unwrap_or_else(|_| serde_json::json!({}));
            let expected_response : models::GetMarketDetailResponse = serde_json::from_value(resp_json.clone()).expect("should parse into models::GetMarketDetailResponse");

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

            let params = GetMarketDetailParams::builder(4229564).build().unwrap();

            let resp_json: Value = serde_json::from_str(r#"{"marketTopicId":4229564,"vendor":"PREDICT_FUN","chainId":"56","slug":"btc-price-1h-up-or-down","title":"BTC Price 1h Up or Down?","question":"Will BTC price go UP in the next 1 hour?","description":"Resolves YES if BTC spot price is higher than the starting price at resolution time.","imageUrl":"https://cdn.example.com/prediction/btc-1h.png","topicType":"FLAT","chartType":"CRYPTO_UP_DOWN","symbol":"BTCUSDT","variantData":{"type":"CRYPTO_UP_DOWN","startPrice":"67890.12","endPrice":"endPrice","priceFeedId":"0xpricefeedid123","priceFeedProvider":"BINANCE","priceFeedSymbol":"BTCUSDT"},"participantCount":3420,"collateral":"USDT","feeRateBps":200,"slippageBps":1200,"isYieldBearing":false,"tradeVolume":"158234.56","liquidity":"45000.00","publishedAt":1748100000000,"startDate":1748131200000,"endDate":1748134800000,"status":"REGISTERED","timeline":[{"marketTopicId":4229560,"startDate":1748127600000,"endDate":1748131200000}],"markets":[{"marketId":5567895,"externalId":"ext_001","title":"UP","question":"Will BTC go UP?","description":"Resolves YES if BTC price increases.","conditionId":"0xabc123","status":"REGISTERED","tradingStatus":"OPEN","tradeVolume":"90000.00","liquidity":"25000.00","decimalPrecision":2,"outcomes":[{"name":"YES","price":"0.52","chance":"0.52","index":0,"tokenId":"112233"}]}]}"#).unwrap_or_else(|_| serde_json::json!({}));
            let expected_response : models::GetMarketDetailResponse = serde_json::from_value(resp_json.clone()).expect("should parse into models::GetMarketDetailResponse");

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

            let params = GetMarketDetailParams::builder(4229564).build().unwrap();

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

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


            let resp_json: Value = serde_json::from_str(r#"{"categories":[{"id":"crypto","name":"Crypto","icon":"crypto_icon","order":1,"subcategories":[{"id":"up-down","name":"Up/Down","icon":"updown_icon","order":1}]}]}"#).unwrap_or_else(|_| serde_json::json!({}));
            let expected_response : models::ListPredictionCategoriesResponse = serde_json::from_value(resp_json.clone()).expect("should parse into models::ListPredictionCategoriesResponse");

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


            let resp_json: Value = serde_json::from_str(r#"{"categories":[{"id":"crypto","name":"Crypto","icon":"crypto_icon","order":1,"subcategories":[{"id":"up-down","name":"Up/Down","icon":"updown_icon","order":1}]}]}"#).unwrap_or_else(|_| serde_json::json!({}));
            let expected_response : models::ListPredictionCategoriesResponse = serde_json::from_value(resp_json.clone()).expect("should parse into models::ListPredictionCategoriesResponse");

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

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

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

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

            let resp_json: Value = serde_json::from_str(r#"{"marketTopics":[{"marketTopicId":4229564,"vendor":"PREDICT_FUN","chainId":"56","slug":"btc-price-1h-up-or-down","title":"BTC Price 1h Up or Down?","question":"Will BTC price go UP in the next 1 hour?","description":"Resolves YES if BTC spot price is higher than the starting price at resolution time.","imageUrl":"https://cdn.example.com/prediction/btc-1h.png","topicType":"FLAT","chartType":"CRYPTO_UP_DOWN","symbol":"BTCUSDT","participantCount":3420,"collateral":"USDT","feeRateBps":200,"slippageBps":1200,"isYieldBearing":false,"tradeVolume":"158234.56","liquidity":"45000.00","publishedAt":1748100000000,"startDate":1748131200000,"endDate":1748134800000,"status":"REGISTERED","markets":[{}]}],"total":128,"offset":0,"limit":20,"hasMore":true}"#).unwrap_or_else(|_| serde_json::json!({}));
            let expected_response : models::ListPredictionMarketsResponse = serde_json::from_value(resp_json.clone()).expect("should parse into models::ListPredictionMarketsResponse");

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

            let params = ListPredictionMarketsParams::builder().l1_category("crypto".to_string()).l2_category("up-down".to_string()).sort_by(ListPredictionMarketsSortByEnum::Recommended).order_by(ListPredictionMarketsOrderByEnum::Asc).offset(0).limit(20).build().unwrap();

            let resp_json: Value = serde_json::from_str(r#"{"marketTopics":[{"marketTopicId":4229564,"vendor":"PREDICT_FUN","chainId":"56","slug":"btc-price-1h-up-or-down","title":"BTC Price 1h Up or Down?","question":"Will BTC price go UP in the next 1 hour?","description":"Resolves YES if BTC spot price is higher than the starting price at resolution time.","imageUrl":"https://cdn.example.com/prediction/btc-1h.png","topicType":"FLAT","chartType":"CRYPTO_UP_DOWN","symbol":"BTCUSDT","participantCount":3420,"collateral":"USDT","feeRateBps":200,"slippageBps":1200,"isYieldBearing":false,"tradeVolume":"158234.56","liquidity":"45000.00","publishedAt":1748100000000,"startDate":1748131200000,"endDate":1748134800000,"status":"REGISTERED","markets":[{}]}],"total":128,"offset":0,"limit":20,"hasMore":true}"#).unwrap_or_else(|_| serde_json::json!({}));
            let expected_response : models::ListPredictionMarketsResponse = serde_json::from_value(resp_json.clone()).expect("should parse into models::ListPredictionMarketsResponse");

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

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

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

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

            let params = MarketSearchParams::builder("BTC price".to_string(),).build().unwrap();

            let resp_json: Value = serde_json::from_str(r#"[{"marketTopicId":4229564,"vendor":"PREDICT_FUN","chainId":"56","slug":"btc-price-1h-up-or-down","title":"BTC Price 1h Up or Down?","question":"Will BTC price go UP in the next 1 hour?","description":"Resolves YES if BTC spot price is higher than the starting price.","topicType":"FLAT","chartType":"CRYPTO_UP_DOWN","symbol":"BTCUSDT","participantCount":3420,"collateral":"USDT","tradeVolume":"158234.56","liquidity":"45000.00","startDate":1748131200000,"endDate":1748134800000,"status":"REGISTERED","markets":[{}]}]"#).unwrap_or_else(|_| serde_json::json!({}));
            let expected_response : Vec<models::MarketSearchResponseInner> = serde_json::from_value(resp_json.clone()).expect("should parse into Vec<models::MarketSearchResponseInner>");

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

            let params = MarketSearchParams::builder("BTC price".to_string(),).top_k(20).build().unwrap();

            let resp_json: Value = serde_json::from_str(r#"[{"marketTopicId":4229564,"vendor":"PREDICT_FUN","chainId":"56","slug":"btc-price-1h-up-or-down","title":"BTC Price 1h Up or Down?","question":"Will BTC price go UP in the next 1 hour?","description":"Resolves YES if BTC spot price is higher than the starting price.","topicType":"FLAT","chartType":"CRYPTO_UP_DOWN","symbol":"BTCUSDT","participantCount":3420,"collateral":"USDT","tradeVolume":"158234.56","liquidity":"45000.00","startDate":1748131200000,"endDate":1748134800000,"status":"REGISTERED","markets":[{}]}]"#).unwrap_or_else(|_| serde_json::json!({}));
            let expected_response : Vec<models::MarketSearchResponseInner> = serde_json::from_value(resp_json.clone()).expect("should parse into Vec<models::MarketSearchResponseInner>");

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

            let params = MarketSearchParams::builder("BTC price".to_string())
                .build()
                .unwrap();

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

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

            let params = QueryLastTradePriceParams::builder(5567895).build().unwrap();

            let resp_json: Value =
                serde_json::from_str(r#"{"marketId":5567895,"lastTradePrice":"0.52"}"#)
                    .unwrap_or_else(|_| serde_json::json!({}));
            let expected_response: models::QueryLastTradePriceResponse =
                serde_json::from_value(resp_json.clone())
                    .expect("should parse into models::QueryLastTradePriceResponse");

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

            let params = QueryLastTradePriceParams::builder(5567895).build().unwrap();

            let resp_json: Value =
                serde_json::from_str(r#"{"marketId":5567895,"lastTradePrice":"0.52"}"#)
                    .unwrap_or_else(|_| serde_json::json!({}));
            let expected_response: models::QueryLastTradePriceResponse =
                serde_json::from_value(resp_json.clone())
                    .expect("should parse into models::QueryLastTradePriceResponse");

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

            let params = QueryLastTradePriceParams::builder(5567895).build().unwrap();

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

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

            let params = QueryOrderBookParams::builder("predict_fun".to_string(),5567895,"112233".to_string()).build().unwrap();

            let resp_json: Value = serde_json::from_str(r#"{"outcome":"YES","tokenId":"112233","timestamp":1748131800000,"bids":[{"price":"0.51","size":"5000.00"}],"asks":[{"price":"0.52","size":"3000.00"}]}"#).unwrap_or_else(|_| serde_json::json!({}));
            let expected_response : models::QueryOrderBookResponse = serde_json::from_value(resp_json.clone()).expect("should parse into models::QueryOrderBookResponse");

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

            let params = QueryOrderBookParams::builder("predict_fun".to_string(),5567895,"112233".to_string()).build().unwrap();

            let resp_json: Value = serde_json::from_str(r#"{"outcome":"YES","tokenId":"112233","timestamp":1748131800000,"bids":[{"price":"0.51","size":"5000.00"}],"asks":[{"price":"0.52","size":"3000.00"}]}"#).unwrap_or_else(|_| serde_json::json!({}));
            let expected_response : models::QueryOrderBookResponse = serde_json::from_value(resp_json.clone()).expect("should parse into models::QueryOrderBookResponse");

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

            let params = QueryOrderBookParams::builder(
                "predict_fun".to_string(),
                5567895,
                "112233".to_string(),
            )
            .build()
            .unwrap();

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