/*
 * 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 RedeemApi: Send + Sync {
    async fn batch_redeem(
        &self,
        params: BatchRedeemParams,
    ) -> anyhow::Result<RestApiResponse<models::BatchRedeemResponse>>;
    async fn get_redeem_status(
        &self,
        params: GetRedeemStatusParams,
    ) -> anyhow::Result<RestApiResponse<models::GetRedeemStatusResponse>>;
}

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

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

/// Request parameters for the [`batch_redeem`] operation.
///
/// This struct holds all of the inputs you can pass when calling
/// [`batch_redeem`](#method.batch_redeem).
#[derive(Clone, Debug, Builder)]
#[builder(pattern = "owned", build_fn(error = "ParamBuildError"))]
pub struct BatchRedeemParams {
    /// User's prediction wallet address
    ///
    /// This field is **required.
    #[builder(setter(into))]
    pub wallet_address: String,
    /// Wallet ID
    ///
    /// This field is **required.
    #[builder(setter(into))]
    pub wallet_id: String,
    /// List of prediction token IDs to redeem. Not empty. Example: `tokenIds=112233&tokenIds=112234`
    ///
    /// This field is **required.
    #[builder(setter(into))]
    pub token_ids: Vec<String>,
    /// Chain ID. Default `56` (BSC)
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub chain_id: Option<String>,
}

impl BatchRedeemParams {
    /// Create a builder for [`batch_redeem`].
    ///
    /// Required parameters:
    ///
    /// * `wallet_address` — User's prediction wallet address
    /// * `wallet_id` — Wallet ID
    /// * `token_ids` — List of prediction token IDs to redeem. Not empty. Example: `tokenIds=112233&tokenIds=112234`
    ///
    #[must_use]
    pub fn builder(
        wallet_address: String,
        wallet_id: String,
        token_ids: Vec<String>,
    ) -> BatchRedeemParamsBuilder {
        BatchRedeemParamsBuilder::default()
            .wallet_address(wallet_address)
            .wallet_id(wallet_id)
            .token_ids(token_ids)
    }
}
/// Request parameters for the [`get_redeem_status`] operation.
///
/// This struct holds all of the inputs you can pass when calling
/// [`get_redeem_status`](#method.get_redeem_status).
#[derive(Clone, Debug, Builder)]
#[builder(pattern = "owned", build_fn(error = "ParamBuildError"))]
pub struct GetRedeemStatusParams {
    /// User's prediction wallet address
    ///
    /// This field is **required.
    #[builder(setter(into))]
    pub wallet_address: String,
    /// Redeem transaction hash
    ///
    /// This field is **required.
    #[builder(setter(into))]
    pub tx_hash: String,
    /// Request validity window in milliseconds
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub recv_window: Option<i64>,
}

impl GetRedeemStatusParams {
    /// Create a builder for [`get_redeem_status`].
    ///
    /// Required parameters:
    ///
    /// * `wallet_address` — User's prediction wallet address
    /// * `tx_hash` — Redeem transaction hash
    ///
    #[must_use]
    pub fn builder(wallet_address: String, tx_hash: String) -> GetRedeemStatusParamsBuilder {
        GetRedeemStatusParamsBuilder::default()
            .wallet_address(wallet_address)
            .tx_hash(tx_hash)
    }
}

#[async_trait]
impl RedeemApi for RedeemApiClient {
    async fn batch_redeem(
        &self,
        params: BatchRedeemParams,
    ) -> anyhow::Result<RestApiResponse<models::BatchRedeemResponse>> {
        let BatchRedeemParams {
            wallet_address,
            wallet_id,
            token_ids,
            chain_id,
        } = params;

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

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

        query_params.insert("walletId".to_string(), json!(wallet_id));

        query_params.insert("tokenIds".to_string(), json!(token_ids));

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

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

    async fn get_redeem_status(
        &self,
        params: GetRedeemStatusParams,
    ) -> anyhow::Result<RestApiResponse<models::GetRedeemStatusResponse>> {
        let GetRedeemStatusParams {
            wallet_address,
            tx_hash,
            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("txHash".to_string(), json!(tx_hash));

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

        send_request::<models::GetRedeemStatusResponse>(
            &self.configuration,
            "/sapi/v1/w3w/wallet/prediction/redeem/status",
            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 MockRedeemApiClient {
        force_error: bool,
    }

    #[async_trait]
    impl RedeemApi for MockRedeemApiClient {
        async fn batch_redeem(
            &self,
            _params: BatchRedeemParams,
        ) -> anyhow::Result<RestApiResponse<models::BatchRedeemResponse>> {
            if self.force_error {
                return Err(ConnectorError::ConnectorClientError {
                    msg: "ResponseError".to_string(),
                    code: None,
                }
                .into());
            }

            let resp_json: Value = serde_json::from_str(r#"{"batchId":"batch_20260525_redeem_001","results":[{"requestId":"req_001","txHash":"0xabc123def456789abcdef123456789abcdef123456789abcdef123456789abcd","status":"PENDING","error":"error"}]}"#).unwrap_or_else(|_| serde_json::json!({}));
            let dummy_response: models::BatchRedeemResponse =
                serde_json::from_value(resp_json.clone())
                    .expect("should parse into models::BatchRedeemResponse");

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

            let resp_json: Value = serde_json::from_str(r#"{"txHash":"0xabc123def456789abcdef123456789abcdef123456789abcdef123456789abcd","status":"CONFIRMED"}"#).unwrap_or_else(|_| serde_json::json!({}));
            let dummy_response: models::GetRedeemStatusResponse =
                serde_json::from_value(resp_json.clone())
                    .expect("should parse into models::GetRedeemStatusResponse");

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

            let params = BatchRedeemParams::builder("0x12e32db8817e292508c34111cbc4b23340df542c".to_string(),"5b5c1ec3be4e4416a5872b21c1ca5d20".to_string(),["112233".to_string(),].to_vec(),).build().unwrap();

            let resp_json: Value = serde_json::from_str(r#"{"batchId":"batch_20260525_redeem_001","results":[{"requestId":"req_001","txHash":"0xabc123def456789abcdef123456789abcdef123456789abcdef123456789abcd","status":"PENDING","error":"error"}]}"#).unwrap_or_else(|_| serde_json::json!({}));
            let expected_response : models::BatchRedeemResponse = serde_json::from_value(resp_json.clone()).expect("should parse into models::BatchRedeemResponse");

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

            let params = BatchRedeemParams::builder("0x12e32db8817e292508c34111cbc4b23340df542c".to_string(),"5b5c1ec3be4e4416a5872b21c1ca5d20".to_string(),["112233".to_string(),].to_vec(),).chain_id("56".to_string()).build().unwrap();

            let resp_json: Value = serde_json::from_str(r#"{"batchId":"batch_20260525_redeem_001","results":[{"requestId":"req_001","txHash":"0xabc123def456789abcdef123456789abcdef123456789abcdef123456789abcd","status":"PENDING","error":"error"}]}"#).unwrap_or_else(|_| serde_json::json!({}));
            let expected_response : models::BatchRedeemResponse = serde_json::from_value(resp_json.clone()).expect("should parse into models::BatchRedeemResponse");

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

            let params = BatchRedeemParams::builder(
                "0x12e32db8817e292508c34111cbc4b23340df542c".to_string(),
                "5b5c1ec3be4e4416a5872b21c1ca5d20".to_string(),
                ["112233".to_string()].to_vec(),
            )
            .build()
            .unwrap();

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

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

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

            let resp_json: Value = serde_json::from_str(r#"{"txHash":"0xabc123def456789abcdef123456789abcdef123456789abcdef123456789abcd","status":"CONFIRMED"}"#).unwrap_or_else(|_| serde_json::json!({}));
            let expected_response : models::GetRedeemStatusResponse = serde_json::from_value(resp_json.clone()).expect("should parse into models::GetRedeemStatusResponse");

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

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

            let resp_json: Value = serde_json::from_str(r#"{"txHash":"0xabc123def456789abcdef123456789abcdef123456789abcdef123456789abcd","status":"CONFIRMED"}"#).unwrap_or_else(|_| serde_json::json!({}));
            let expected_response : models::GetRedeemStatusResponse = serde_json::from_value(resp_json.clone()).expect("should parse into models::GetRedeemStatusResponse");

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

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

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