/*
 * 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 PositionApi: Send + Sync {
    async fn get_position_by_token(
        &self,
        params: GetPositionByTokenParams,
    ) -> anyhow::Result<RestApiResponse<models::GetPositionByTokenResponse>>;
    async fn query_pn_l(
        &self,
        params: QueryPnLParams,
    ) -> anyhow::Result<RestApiResponse<models::QueryPnLResponse>>;
    async fn query_positions(
        &self,
        params: QueryPositionsParams,
    ) -> anyhow::Result<RestApiResponse<models::QueryPositionsResponse>>;
    async fn query_positions_by_filter(
        &self,
        params: QueryPositionsByFilterParams,
    ) -> anyhow::Result<RestApiResponse<models::QueryPositionsByFilterResponse>>;
    async fn query_settled_position_history(
        &self,
        params: QuerySettledPositionHistoryParams,
    ) -> anyhow::Result<RestApiResponse<models::QuerySettledPositionHistoryResponse>>;
}

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

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

/// Request parameters for the [`get_position_by_token`] operation.
///
/// This struct holds all of the inputs you can pass when calling
/// [`get_position_by_token`](#method.get_position_by_token).
#[derive(Clone, Debug, Builder)]
#[builder(pattern = "owned", build_fn(error = "ParamBuildError"))]
pub struct GetPositionByTokenParams {
    /// User's prediction wallet address
    ///
    /// This field is **required.
    #[builder(setter(into))]
    pub wallet_address: String,
    /// Prediction outcome token ID
    ///
    /// This field is **required.
    #[builder(setter(into))]
    pub token_id: String,
    /// Request validity window in milliseconds
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub recv_window: Option<i64>,
}

impl GetPositionByTokenParams {
    /// Create a builder for [`get_position_by_token`].
    ///
    /// Required parameters:
    ///
    /// * `wallet_address` — User's prediction wallet address
    /// * `token_id` — Prediction outcome token ID
    ///
    #[must_use]
    pub fn builder(wallet_address: String, token_id: String) -> GetPositionByTokenParamsBuilder {
        GetPositionByTokenParamsBuilder::default()
            .wallet_address(wallet_address)
            .token_id(token_id)
    }
}
/// Request parameters for the [`query_pn_l`] operation.
///
/// This struct holds all of the inputs you can pass when calling
/// [`query_pn_l`](#method.query_pn_l).
#[derive(Clone, Debug, Builder)]
#[builder(pattern = "owned", build_fn(error = "ParamBuildError"))]
pub struct QueryPnLParams {
    /// User's prediction wallet address
    ///
    /// This field is **required.
    #[builder(setter(into))]
    pub wallet_address: String,
    /// Filter by prediction token ID
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub token_id: Option<String>,
    /// Filter by market ID. Must be > 0
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub market_id: Option<i64>,
    /// Filter by market topic ID. Must be > 0
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub market_topic_id: Option<i64>,
    /// If `true`, return only active (unresolved) positions
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub active_only: Option<bool>,
    /// Request validity window in milliseconds
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub recv_window: Option<i64>,
}

impl QueryPnLParams {
    /// Create a builder for [`query_pn_l`].
    ///
    /// Required parameters:
    ///
    /// * `wallet_address` — User's prediction wallet address
    ///
    #[must_use]
    pub fn builder(wallet_address: String) -> QueryPnLParamsBuilder {
        QueryPnLParamsBuilder::default().wallet_address(wallet_address)
    }
}
/// Request parameters for the [`query_positions`] operation.
///
/// This struct holds all of the inputs you can pass when calling
/// [`query_positions`](#method.query_positions).
#[derive(Clone, Debug, Builder)]
#[builder(pattern = "owned", build_fn(error = "ParamBuildError"))]
pub struct QueryPositionsParams {
    /// User's prediction wallet address
    ///
    /// This field is **required.
    #[builder(setter(into))]
    pub wallet_address: String,
    /// Position status tab. Values from `PositionQueryType`. Default `ONGOING`
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub tab: Option<String>,
    /// 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>,
    /// Request validity window in milliseconds
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub recv_window: Option<i64>,
}

impl QueryPositionsParams {
    /// Create a builder for [`query_positions`].
    ///
    /// Required parameters:
    ///
    /// * `wallet_address` — User's prediction wallet address
    ///
    #[must_use]
    pub fn builder(wallet_address: String) -> QueryPositionsParamsBuilder {
        QueryPositionsParamsBuilder::default().wallet_address(wallet_address)
    }
}
/// Request parameters for the [`query_positions_by_filter`] operation.
///
/// This struct holds all of the inputs you can pass when calling
/// [`query_positions_by_filter`](#method.query_positions_by_filter).
#[derive(Clone, Debug, Builder, Default)]
#[builder(pattern = "owned", build_fn(error = "ParamBuildError"))]
pub struct QueryPositionsByFilterParams {
    /// User's prediction wallet address
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub wallet_address: Option<String>,
    /// Filter by market topic ID
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub market_topic_id: Option<i64>,
    /// Request validity window in milliseconds
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub recv_window: Option<i64>,
}

impl QueryPositionsByFilterParams {
    /// Create a builder for [`query_positions_by_filter`].
    ///
    #[must_use]
    pub fn builder() -> QueryPositionsByFilterParamsBuilder {
        QueryPositionsByFilterParamsBuilder::default()
    }
}
/// Request parameters for the [`query_settled_position_history`] operation.
///
/// This struct holds all of the inputs you can pass when calling
/// [`query_settled_position_history`](#method.query_settled_position_history).
#[derive(Clone, Debug, Builder)]
#[builder(pattern = "owned", build_fn(error = "ParamBuildError"))]
pub struct QuerySettledPositionHistoryParams {
    /// User's prediction wallet address
    ///
    /// This field is **required.
    #[builder(setter(into))]
    pub wallet_address: String,
    /// Filter by level-1 category
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub l1_category: Option<String>,
    /// Settlement result filter
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub result: Option<i32>,
    /// Start date. Format: `yyyy-MM-dd`. Must be ≤ `endDate`
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub start_date: Option<String>,
    /// End date. Format: `yyyy-MM-dd`. Must be ≥ `startDate`
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub end_date: Option<String>,
    /// 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>,
    /// Request validity window in milliseconds
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub recv_window: Option<i64>,
}

impl QuerySettledPositionHistoryParams {
    /// Create a builder for [`query_settled_position_history`].
    ///
    /// Required parameters:
    ///
    /// * `wallet_address` — User's prediction wallet address
    ///
    #[must_use]
    pub fn builder(wallet_address: String) -> QuerySettledPositionHistoryParamsBuilder {
        QuerySettledPositionHistoryParamsBuilder::default().wallet_address(wallet_address)
    }
}

#[async_trait]
impl PositionApi for PositionApiClient {
    async fn get_position_by_token(
        &self,
        params: GetPositionByTokenParams,
    ) -> anyhow::Result<RestApiResponse<models::GetPositionByTokenResponse>> {
        let GetPositionByTokenParams {
            wallet_address,
            token_id,
            recv_window,
        } = params;

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

        query_params.insert("walletAddress".to_string(), json!(wallet_address));

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

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

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

    async fn query_pn_l(
        &self,
        params: QueryPnLParams,
    ) -> anyhow::Result<RestApiResponse<models::QueryPnLResponse>> {
        let QueryPnLParams {
            wallet_address,
            token_id,
            market_id,
            market_topic_id,
            active_only,
            recv_window,
        } = params;

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

        query_params.insert("walletAddress".to_string(), json!(wallet_address));

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

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

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

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

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

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

    async fn query_positions(
        &self,
        params: QueryPositionsParams,
    ) -> anyhow::Result<RestApiResponse<models::QueryPositionsResponse>> {
        let QueryPositionsParams {
            wallet_address,
            tab,
            offset,
            limit,
            recv_window,
        } = params;

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

        query_params.insert("walletAddress".to_string(), json!(wallet_address));

        if let Some(rw) = tab {
            query_params.insert("tab".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));
        }

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

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

    async fn query_positions_by_filter(
        &self,
        params: QueryPositionsByFilterParams,
    ) -> anyhow::Result<RestApiResponse<models::QueryPositionsByFilterResponse>> {
        let QueryPositionsByFilterParams {
            wallet_address,
            market_topic_id,
            recv_window,
        } = params;

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

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

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

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

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

    async fn query_settled_position_history(
        &self,
        params: QuerySettledPositionHistoryParams,
    ) -> anyhow::Result<RestApiResponse<models::QuerySettledPositionHistoryResponse>> {
        let QuerySettledPositionHistoryParams {
            wallet_address,
            l1_category,
            result,
            start_date,
            end_date,
            offset,
            limit,
            recv_window,
        } = params;

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

        query_params.insert("walletAddress".to_string(), json!(wallet_address));

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

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

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

        if let Some(rw) = end_date {
            query_params.insert("endDate".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));
        }

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

        send_request::<models::QuerySettledPositionHistoryResponse>(
            &self.configuration,
            "/sapi/v1/w3w/wallet/prediction/position/settled-history",
            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 MockPositionApiClient {
        force_error: bool,
    }

    #[async_trait]
    impl PositionApi for MockPositionApiClient {
        async fn get_position_by_token(
            &self,
            _params: GetPositionByTokenParams,
        ) -> anyhow::Result<RestApiResponse<models::GetPositionByTokenResponse>> {
            if self.force_error {
                return Err(ConnectorError::ConnectorClientError {
                    msg: "ResponseError".to_string(),
                    code: None,
                }
                .into());
            }

            let resp_json: Value = serde_json::from_str(r#"{"position":{"positionId":1001,"vendor":"PREDICT_FUN","chainId":"56","tokenId":"112233","collateralSymbol":"USDT","topicType":"FLAT","marketTopicId":4229564,"marketId":5567895,"marketTopicTitle":"BTC Price 1h Up or Down?","marketTitle":"UP","outcomeName":"YES","outcomeIndex":0,"shares":"1923.07","avgPrice":"0.52","totalCost":"1.00","value":"1.06","currentPrice":"0.55","positionStatus":"OPEN","endDate":1748134800000,"unrealizedPnl":"0.06","realizedPnl":"0.00","pnl":"0.06","createdTime":1748131500000,"updatedTime":1748132000000}}"#).unwrap_or_else(|_| serde_json::json!({}));
            let dummy_response: models::GetPositionByTokenResponse =
                serde_json::from_value(resp_json.clone())
                    .expect("should parse into models::GetPositionByTokenResponse");

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

            let resp_json: Value = serde_json::from_str(r#"{"chainId":"56","walletAddress":"0x12e32db8817e292508c34111cbc4b23340df542c","pnl":"pnl","pnlList":[{"id":10001,"walletAddress":"0x12e32db8817e292508c34111cbc4b23340df542c","marketTopicId":4229564,"marketId":5567895,"tokenId":"112233","vendor":"PREDICT_FUN","currentShares":"1923.07","avgPrice":"0.52","currentPrice":"0.55","realizedPnl":"0.00","unrealizedPnl":"0.06","totalPnl":"0.06","pnlPercentage":"6.00","isResolved":false}],"totalCount":1,"totalRealizedPnl":"0.00","totalUnrealizedPnl":"0.06","totalPnl":"0.06"}"#).unwrap_or_else(|_| serde_json::json!({}));
            let dummy_response: models::QueryPnLResponse =
                serde_json::from_value(resp_json.clone())
                    .expect("should parse into models::QueryPnLResponse");

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

            let resp_json: Value = serde_json::from_str(r#"{"summary":{"totalValue":"1523.45","positionValue":"523.45","walletBalance":"1000.00","totalClaimableAmount":"50.00","todayRealizedPnl":"15.30","todayRealizedPnlPercent":"3.10","todayTotalCost":"493.55"},"counts":{"ongoingCount":3,"endedCount":12,"pendingClaimCount":1},"positions":[{"positionId":1001,"vendor":"PREDICT_FUN","chainId":"56","tokenId":"112233","collateralSymbol":"USDT","topicType":"FLAT","marketTopicId":4229564,"marketId":5567895,"marketTopicTitle":"BTC Price 1h Up or Down?","marketTitle":"UP","outcomeName":"YES","outcomeIndex":0,"shares":"1923.07","avgPrice":"0.52","totalCost":"1.00","value":"1.06","currentPrice":"0.55","toWin":"1923.07","positionStatus":"OPEN","canClaim":false,"endDate":1748134800000,"unrealizedPnl":"0.06","unrealizedPnlPercent":"6.00","realizedPnl":"0.00","pnl":"0.06","createdTime":1748131500000,"updatedTime":1748132000000}]}"#).unwrap_or_else(|_| serde_json::json!({}));
            let dummy_response: models::QueryPositionsResponse =
                serde_json::from_value(resp_json.clone())
                    .expect("should parse into models::QueryPositionsResponse");

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

            let resp_json: Value = serde_json::from_str(r#"{"positions":[{"positionId":1001,"vendor":"PREDICT_FUN","chainId":"56","tokenId":"112233","collateralSymbol":"USDT","topicType":"FLAT","marketTopicId":4229564,"marketId":5567895,"marketTopicTitle":"BTC Price 1h Up or Down?","marketTitle":"UP","outcomeName":"YES","outcomeIndex":0,"shares":"1923.07","avgPrice":"0.52","totalCost":"1.00","value":"1.06","currentPrice":"0.55","positionStatus":"OPEN","endDate":1748134800000,"unrealizedPnl":"0.06","realizedPnl":"0.00","pnl":"0.06","createdTime":1748131500000,"updatedTime":1748132000000}]}"#).unwrap_or_else(|_| serde_json::json!({}));
            let dummy_response: models::QueryPositionsByFilterResponse =
                serde_json::from_value(resp_json.clone())
                    .expect("should parse into models::QueryPositionsByFilterResponse");

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

            let resp_json: Value = serde_json::from_str(r#"{"totalCount":5,"positions":[{"positionId":998,"vendor":"PREDICT_FUN","chainId":"56","tokenId":"112200","collateralSymbol":"USDT","topicType":"FLAT","marketTopicId":4229500,"marketId":5567800,"marketTopicTitle":"BTC Price 1h Up or Down?","marketTitle":"UP","outcomeName":"YES","outcomeIndex":0,"shares":"5000.00","avgPrice":"0.30","totalCost":"1.50","value":"5000.00","currentPrice":"1.00","toWin":"5000.00","positionStatus":"CLAIMED","isWinner":true,"redeemStatus":"CONFIRMED","endDate":1748040000000,"finalOutcome":"YES","realizedPnl":"4998.50","pnl":"4998.50","claimAmount":"5000.00","settledDate":1748040000000,"createdTime":1748020000000,"updatedTime":1748040500000}]}"#).unwrap_or_else(|_| serde_json::json!({}));
            let dummy_response: models::QuerySettledPositionHistoryResponse =
                serde_json::from_value(resp_json.clone())
                    .expect("should parse into models::QuerySettledPositionHistoryResponse");

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

            let params = GetPositionByTokenParams::builder("0x12e32db8817e292508c34111cbc4b23340df542c".to_string(),"112233".to_string(),).build().unwrap();

            let resp_json: Value = serde_json::from_str(r#"{"position":{"positionId":1001,"vendor":"PREDICT_FUN","chainId":"56","tokenId":"112233","collateralSymbol":"USDT","topicType":"FLAT","marketTopicId":4229564,"marketId":5567895,"marketTopicTitle":"BTC Price 1h Up or Down?","marketTitle":"UP","outcomeName":"YES","outcomeIndex":0,"shares":"1923.07","avgPrice":"0.52","totalCost":"1.00","value":"1.06","currentPrice":"0.55","positionStatus":"OPEN","endDate":1748134800000,"unrealizedPnl":"0.06","realizedPnl":"0.00","pnl":"0.06","createdTime":1748131500000,"updatedTime":1748132000000}}"#).unwrap_or_else(|_| serde_json::json!({}));
            let expected_response : models::GetPositionByTokenResponse = serde_json::from_value(resp_json.clone()).expect("should parse into models::GetPositionByTokenResponse");

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

            let params = GetPositionByTokenParams::builder("0x12e32db8817e292508c34111cbc4b23340df542c".to_string(),"112233".to_string(),).recv_window(5000).build().unwrap();

            let resp_json: Value = serde_json::from_str(r#"{"position":{"positionId":1001,"vendor":"PREDICT_FUN","chainId":"56","tokenId":"112233","collateralSymbol":"USDT","topicType":"FLAT","marketTopicId":4229564,"marketId":5567895,"marketTopicTitle":"BTC Price 1h Up or Down?","marketTitle":"UP","outcomeName":"YES","outcomeIndex":0,"shares":"1923.07","avgPrice":"0.52","totalCost":"1.00","value":"1.06","currentPrice":"0.55","positionStatus":"OPEN","endDate":1748134800000,"unrealizedPnl":"0.06","realizedPnl":"0.00","pnl":"0.06","createdTime":1748131500000,"updatedTime":1748132000000}}"#).unwrap_or_else(|_| serde_json::json!({}));
            let expected_response : models::GetPositionByTokenResponse = serde_json::from_value(resp_json.clone()).expect("should parse into models::GetPositionByTokenResponse");

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

            let params = GetPositionByTokenParams::builder(
                "0x12e32db8817e292508c34111cbc4b23340df542c".to_string(),
                "112233".to_string(),
            )
            .build()
            .unwrap();

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

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

            let params = QueryPnLParams::builder("0x12e32db8817e292508c34111cbc4b23340df542c".to_string(),).build().unwrap();

            let resp_json: Value = serde_json::from_str(r#"{"chainId":"56","walletAddress":"0x12e32db8817e292508c34111cbc4b23340df542c","pnl":"pnl","pnlList":[{"id":10001,"walletAddress":"0x12e32db8817e292508c34111cbc4b23340df542c","marketTopicId":4229564,"marketId":5567895,"tokenId":"112233","vendor":"PREDICT_FUN","currentShares":"1923.07","avgPrice":"0.52","currentPrice":"0.55","realizedPnl":"0.00","unrealizedPnl":"0.06","totalPnl":"0.06","pnlPercentage":"6.00","isResolved":false}],"totalCount":1,"totalRealizedPnl":"0.00","totalUnrealizedPnl":"0.06","totalPnl":"0.06"}"#).unwrap_or_else(|_| serde_json::json!({}));
            let expected_response : models::QueryPnLResponse = serde_json::from_value(resp_json.clone()).expect("should parse into models::QueryPnLResponse");

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

            let params = QueryPnLParams::builder("0x12e32db8817e292508c34111cbc4b23340df542c".to_string(),).token_id("112233".to_string()).market_id(5567895).market_topic_id(4229564).active_only(false).recv_window(5000).build().unwrap();

            let resp_json: Value = serde_json::from_str(r#"{"chainId":"56","walletAddress":"0x12e32db8817e292508c34111cbc4b23340df542c","pnl":"pnl","pnlList":[{"id":10001,"walletAddress":"0x12e32db8817e292508c34111cbc4b23340df542c","marketTopicId":4229564,"marketId":5567895,"tokenId":"112233","vendor":"PREDICT_FUN","currentShares":"1923.07","avgPrice":"0.52","currentPrice":"0.55","realizedPnl":"0.00","unrealizedPnl":"0.06","totalPnl":"0.06","pnlPercentage":"6.00","isResolved":false}],"totalCount":1,"totalRealizedPnl":"0.00","totalUnrealizedPnl":"0.06","totalPnl":"0.06"}"#).unwrap_or_else(|_| serde_json::json!({}));
            let expected_response : models::QueryPnLResponse = serde_json::from_value(resp_json.clone()).expect("should parse into models::QueryPnLResponse");

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

            let params =
                QueryPnLParams::builder("0x12e32db8817e292508c34111cbc4b23340df542c".to_string())
                    .build()
                    .unwrap();

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

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

            let params = QueryPositionsParams::builder("0x12e32db8817e292508c34111cbc4b23340df542c".to_string(),).build().unwrap();

            let resp_json: Value = serde_json::from_str(r#"{"summary":{"totalValue":"1523.45","positionValue":"523.45","walletBalance":"1000.00","totalClaimableAmount":"50.00","todayRealizedPnl":"15.30","todayRealizedPnlPercent":"3.10","todayTotalCost":"493.55"},"counts":{"ongoingCount":3,"endedCount":12,"pendingClaimCount":1},"positions":[{"positionId":1001,"vendor":"PREDICT_FUN","chainId":"56","tokenId":"112233","collateralSymbol":"USDT","topicType":"FLAT","marketTopicId":4229564,"marketId":5567895,"marketTopicTitle":"BTC Price 1h Up or Down?","marketTitle":"UP","outcomeName":"YES","outcomeIndex":0,"shares":"1923.07","avgPrice":"0.52","totalCost":"1.00","value":"1.06","currentPrice":"0.55","toWin":"1923.07","positionStatus":"OPEN","canClaim":false,"endDate":1748134800000,"unrealizedPnl":"0.06","unrealizedPnlPercent":"6.00","realizedPnl":"0.00","pnl":"0.06","createdTime":1748131500000,"updatedTime":1748132000000}]}"#).unwrap_or_else(|_| serde_json::json!({}));
            let expected_response : models::QueryPositionsResponse = serde_json::from_value(resp_json.clone()).expect("should parse into models::QueryPositionsResponse");

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

            let params = QueryPositionsParams::builder("0x12e32db8817e292508c34111cbc4b23340df542c".to_string(),).tab("ONGOING".to_string()).offset(0).limit(20).recv_window(5000).build().unwrap();

            let resp_json: Value = serde_json::from_str(r#"{"summary":{"totalValue":"1523.45","positionValue":"523.45","walletBalance":"1000.00","totalClaimableAmount":"50.00","todayRealizedPnl":"15.30","todayRealizedPnlPercent":"3.10","todayTotalCost":"493.55"},"counts":{"ongoingCount":3,"endedCount":12,"pendingClaimCount":1},"positions":[{"positionId":1001,"vendor":"PREDICT_FUN","chainId":"56","tokenId":"112233","collateralSymbol":"USDT","topicType":"FLAT","marketTopicId":4229564,"marketId":5567895,"marketTopicTitle":"BTC Price 1h Up or Down?","marketTitle":"UP","outcomeName":"YES","outcomeIndex":0,"shares":"1923.07","avgPrice":"0.52","totalCost":"1.00","value":"1.06","currentPrice":"0.55","toWin":"1923.07","positionStatus":"OPEN","canClaim":false,"endDate":1748134800000,"unrealizedPnl":"0.06","unrealizedPnlPercent":"6.00","realizedPnl":"0.00","pnl":"0.06","createdTime":1748131500000,"updatedTime":1748132000000}]}"#).unwrap_or_else(|_| serde_json::json!({}));
            let expected_response : models::QueryPositionsResponse = serde_json::from_value(resp_json.clone()).expect("should parse into models::QueryPositionsResponse");

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

            let params = QueryPositionsParams::builder(
                "0x12e32db8817e292508c34111cbc4b23340df542c".to_string(),
            )
            .build()
            .unwrap();

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

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

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

            let resp_json: Value = serde_json::from_str(r#"{"positions":[{"positionId":1001,"vendor":"PREDICT_FUN","chainId":"56","tokenId":"112233","collateralSymbol":"USDT","topicType":"FLAT","marketTopicId":4229564,"marketId":5567895,"marketTopicTitle":"BTC Price 1h Up or Down?","marketTitle":"UP","outcomeName":"YES","outcomeIndex":0,"shares":"1923.07","avgPrice":"0.52","totalCost":"1.00","value":"1.06","currentPrice":"0.55","positionStatus":"OPEN","endDate":1748134800000,"unrealizedPnl":"0.06","realizedPnl":"0.00","pnl":"0.06","createdTime":1748131500000,"updatedTime":1748132000000}]}"#).unwrap_or_else(|_| serde_json::json!({}));
            let expected_response : models::QueryPositionsByFilterResponse = serde_json::from_value(resp_json.clone()).expect("should parse into models::QueryPositionsByFilterResponse");

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

            let params = QueryPositionsByFilterParams::builder().wallet_address("0x12e32db8817e292508c34111cbc4b23340df542c".to_string()).market_topic_id(4229564).recv_window(5000).build().unwrap();

            let resp_json: Value = serde_json::from_str(r#"{"positions":[{"positionId":1001,"vendor":"PREDICT_FUN","chainId":"56","tokenId":"112233","collateralSymbol":"USDT","topicType":"FLAT","marketTopicId":4229564,"marketId":5567895,"marketTopicTitle":"BTC Price 1h Up or Down?","marketTitle":"UP","outcomeName":"YES","outcomeIndex":0,"shares":"1923.07","avgPrice":"0.52","totalCost":"1.00","value":"1.06","currentPrice":"0.55","positionStatus":"OPEN","endDate":1748134800000,"unrealizedPnl":"0.06","realizedPnl":"0.00","pnl":"0.06","createdTime":1748131500000,"updatedTime":1748132000000}]}"#).unwrap_or_else(|_| serde_json::json!({}));
            let expected_response : models::QueryPositionsByFilterResponse = serde_json::from_value(resp_json.clone()).expect("should parse into models::QueryPositionsByFilterResponse");

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

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

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

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

            let params = QuerySettledPositionHistoryParams::builder("0x12e32db8817e292508c34111cbc4b23340df542c".to_string(),).build().unwrap();

            let resp_json: Value = serde_json::from_str(r#"{"totalCount":5,"positions":[{"positionId":998,"vendor":"PREDICT_FUN","chainId":"56","tokenId":"112200","collateralSymbol":"USDT","topicType":"FLAT","marketTopicId":4229500,"marketId":5567800,"marketTopicTitle":"BTC Price 1h Up or Down?","marketTitle":"UP","outcomeName":"YES","outcomeIndex":0,"shares":"5000.00","avgPrice":"0.30","totalCost":"1.50","value":"5000.00","currentPrice":"1.00","toWin":"5000.00","positionStatus":"CLAIMED","isWinner":true,"redeemStatus":"CONFIRMED","endDate":1748040000000,"finalOutcome":"YES","realizedPnl":"4998.50","pnl":"4998.50","claimAmount":"5000.00","settledDate":1748040000000,"createdTime":1748020000000,"updatedTime":1748040500000}]}"#).unwrap_or_else(|_| serde_json::json!({}));
            let expected_response : models::QuerySettledPositionHistoryResponse = serde_json::from_value(resp_json.clone()).expect("should parse into models::QuerySettledPositionHistoryResponse");

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

            let params = QuerySettledPositionHistoryParams::builder("0x12e32db8817e292508c34111cbc4b23340df542c".to_string(),).l1_category("crypto".to_string()).result(1).start_date("2026-05-01".to_string()).end_date("2026-05-25".to_string()).offset(0).limit(20).recv_window(5000).build().unwrap();

            let resp_json: Value = serde_json::from_str(r#"{"totalCount":5,"positions":[{"positionId":998,"vendor":"PREDICT_FUN","chainId":"56","tokenId":"112200","collateralSymbol":"USDT","topicType":"FLAT","marketTopicId":4229500,"marketId":5567800,"marketTopicTitle":"BTC Price 1h Up or Down?","marketTitle":"UP","outcomeName":"YES","outcomeIndex":0,"shares":"5000.00","avgPrice":"0.30","totalCost":"1.50","value":"5000.00","currentPrice":"1.00","toWin":"5000.00","positionStatus":"CLAIMED","isWinner":true,"redeemStatus":"CONFIRMED","endDate":1748040000000,"finalOutcome":"YES","realizedPnl":"4998.50","pnl":"4998.50","claimAmount":"5000.00","settledDate":1748040000000,"createdTime":1748020000000,"updatedTime":1748040500000}]}"#).unwrap_or_else(|_| serde_json::json!({}));
            let expected_response : models::QuerySettledPositionHistoryResponse = serde_json::from_value(resp_json.clone()).expect("should parse into models::QuerySettledPositionHistoryResponse");

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

            let params = QuerySettledPositionHistoryParams::builder(
                "0x12e32db8817e292508c34111cbc4b23340df542c".to_string(),
            )
            .build()
            .unwrap();

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