/*
 * Binance Spot WebSocket API
 *
 * OpenAPI Specifications for the Binance Spot WebSocket API
 *
 * API documents:
 * - [Github web-socket-api documentation file](https://github.com/binance/binance-spot-api-docs/blob/master/web-socket-api.md)
 * - [General API information for web-socket-api on website](https://developers.binance.com/docs/binance-spot-api-docs/web-socket-api/general-api-information)
 *
 *
 * 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 anyhow::Context;
use async_trait::async_trait;
use derive_builder::Builder;
use rust_decimal::prelude::*;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::{collections::BTreeMap, sync::Arc};

use crate::common::{
    errors::WebsocketError,
    models::{ParamBuildError, WebsocketApiResponse},
    utils::remove_empty_value,
    websocket::{WebsocketApi, WebsocketMessageSendOptions},
};
use crate::spot::websocket_api::models;

#[async_trait]
pub trait AuthApi: Send + Sync {
    async fn session_logon(
        &self,
        params: SessionLogonParams,
    ) -> anyhow::Result<Vec<WebsocketApiResponse<Box<models::SessionLogonResponseResult>>>>;
    async fn session_logout(
        &self,
        params: SessionLogoutParams,
    ) -> anyhow::Result<Vec<WebsocketApiResponse<Box<models::SessionLogoutResponseResult>>>>;
    async fn session_status(
        &self,
        params: SessionStatusParams,
    ) -> anyhow::Result<WebsocketApiResponse<Box<models::SessionStatusResponseResult>>>;
}

#[derive(Clone)]
pub struct AuthApiClient {
    websocket_api_base: Arc<WebsocketApi>,
}

impl AuthApiClient {
    pub fn new(websocket_api_base: Arc<WebsocketApi>) -> Self {
        Self { websocket_api_base }
    }
}

/// Request parameters for the [`session_logon`] operation.
///
/// This struct holds all of the inputs you can pass when calling
/// [`session_logon`](#method.session_logon).
#[derive(Clone, Debug, Builder, Default)]
#[builder(pattern = "owned", build_fn(error = "ParamBuildError"))]
pub struct SessionLogonParams {
    /// Unique WebSocket request ID.
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub id: Option<String>,
    /// The value cannot be greater than `60000`. <br> Supports up to three decimal places of precision (e.g., 6000.346) so that microseconds may be specified.
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub recv_window: Option<rust_decimal::Decimal>,
}

impl SessionLogonParams {
    /// Create a builder for [`session_logon`].
    ///
    #[must_use]
    pub fn builder() -> SessionLogonParamsBuilder {
        SessionLogonParamsBuilder::default()
    }
}
/// Request parameters for the [`session_logout`] operation.
///
/// This struct holds all of the inputs you can pass when calling
/// [`session_logout`](#method.session_logout).
#[derive(Clone, Debug, Builder, Default)]
#[builder(pattern = "owned", build_fn(error = "ParamBuildError"))]
pub struct SessionLogoutParams {
    /// Unique WebSocket request ID.
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub id: Option<String>,
}

impl SessionLogoutParams {
    /// Create a builder for [`session_logout`].
    ///
    #[must_use]
    pub fn builder() -> SessionLogoutParamsBuilder {
        SessionLogoutParamsBuilder::default()
    }
}
/// Request parameters for the [`session_status`] operation.
///
/// This struct holds all of the inputs you can pass when calling
/// [`session_status`](#method.session_status).
#[derive(Clone, Debug, Builder, Default)]
#[builder(pattern = "owned", build_fn(error = "ParamBuildError"))]
pub struct SessionStatusParams {
    /// Unique WebSocket request ID.
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub id: Option<String>,
}

impl SessionStatusParams {
    /// Create a builder for [`session_status`].
    ///
    #[must_use]
    pub fn builder() -> SessionStatusParamsBuilder {
        SessionStatusParamsBuilder::default()
    }
}

#[async_trait]
impl AuthApi for AuthApiClient {
    async fn session_logon(
        &self,
        params: SessionLogonParams,
    ) -> anyhow::Result<Vec<WebsocketApiResponse<Box<models::SessionLogonResponseResult>>>> {
        let SessionLogonParams { id, recv_window } = params;

        let mut payload: BTreeMap<String, Value> = BTreeMap::new();
        if let Some(value) = id {
            payload.insert("id".to_string(), serde_json::json!(value));
        }
        if let Some(value) = recv_window {
            payload.insert("recvWindow".to_string(), serde_json::json!(value));
        }
        let payload = remove_empty_value(payload);

        let response = self
            .websocket_api_base
            .send_message::<Box<models::SessionLogonResponseResult>>(
                "/session.logon".trim_start_matches('/'),
                payload,
                WebsocketMessageSendOptions::new().signed().session_logon(),
            )
            .await
            .map_err(anyhow::Error::from)?
            .into_iter()
            .collect();

        Ok(response)
    }

    async fn session_logout(
        &self,
        params: SessionLogoutParams,
    ) -> anyhow::Result<Vec<WebsocketApiResponse<Box<models::SessionLogoutResponseResult>>>> {
        let SessionLogoutParams { id } = params;

        let mut payload: BTreeMap<String, Value> = BTreeMap::new();
        if let Some(value) = id {
            payload.insert("id".to_string(), serde_json::json!(value));
        }
        let payload = remove_empty_value(payload);

        let response = self
            .websocket_api_base
            .send_message::<Box<models::SessionLogoutResponseResult>>(
                "/session.logout".trim_start_matches('/'),
                payload,
                WebsocketMessageSendOptions::new().session_logout(),
            )
            .await
            .map_err(anyhow::Error::from)?
            .into_iter()
            .collect();

        Ok(response)
    }

    async fn session_status(
        &self,
        params: SessionStatusParams,
    ) -> anyhow::Result<WebsocketApiResponse<Box<models::SessionStatusResponseResult>>> {
        let SessionStatusParams { id } = params;

        let mut payload: BTreeMap<String, Value> = BTreeMap::new();
        if let Some(value) = id {
            payload.insert("id".to_string(), serde_json::json!(value));
        }
        let payload = remove_empty_value(payload);

        self.websocket_api_base
            .send_message::<Box<models::SessionStatusResponseResult>>(
                "/session.status".trim_start_matches('/'),
                payload,
                WebsocketMessageSendOptions::new(),
            )
            .await
            .map_err(anyhow::Error::from)?
            .into_iter()
            .next()
            .ok_or(WebsocketError::NoResponse)
            .map_err(anyhow::Error::from)
    }
}

#[cfg(all(test, feature = "spot"))]
mod tests {
    use super::*;
    use crate::TOKIO_SHARED_RT;
    use crate::common::websocket::{WebsocketApi, WebsocketConnection, WebsocketHandler};
    use crate::config::ConfigurationWebsocketApi;
    use crate::errors::WebsocketError;
    use crate::models::WebsocketApiRateLimit;
    use serde_json::{Value, json};
    use tokio::spawn;
    use tokio::sync::mpsc::{UnboundedReceiver, unbounded_channel};
    use tokio::time::{Duration, timeout};
    use tokio_tungstenite::tungstenite::Message;

    async fn setup() -> (
        Arc<WebsocketApi>,
        Arc<WebsocketConnection>,
        UnboundedReceiver<Message>,
    ) {
        let conn = WebsocketConnection::new("test-conn");
        let (tx, rx) = unbounded_channel::<Message>();
        {
            let mut conn_state = conn.state.lock().await;
            conn_state.ws_write_tx = Some(tx);
        }

        let config = ConfigurationWebsocketApi::builder()
            .api_key("key")
            .api_secret("secret")
            .build()
            .expect("Failed to build configuration");
        let ws_api = WebsocketApi::new(config, vec![conn.clone()]);
        conn.set_handler(ws_api.clone() as Arc<dyn WebsocketHandler>)
            .await;
        ws_api.clone().connect().await.unwrap();

        (ws_api, conn, rx)
    }

    #[test]
    fn session_logon_success() {
        TOKIO_SHARED_RT.block_on(async {
            let (ws_api, conn, mut rx) = setup().await;
            let client = AuthApiClient::new(ws_api.clone());

            let handle = spawn(async move {
                let params = SessionLogonParams::builder().build().unwrap();
                client.session_logon(params).await
            });

            let sent = timeout(Duration::from_secs(1), rx.recv()).await.expect("send should occur").expect("channel closed");
            let Message::Text(text) = sent else { panic!() };
            let v: Value = serde_json::from_str(&text).unwrap();
            let id = v["id"].as_str().unwrap();
            assert_eq!(v["method"], "/session.logon".trim_start_matches('/'));

            let mut resp_json: Value = serde_json::from_str(r#"{"id":"c174a2b1-3f51-4580-b200-8528bd237cb7","status":200,"result":{"apiKey":"vmPUZE6mv9SD5VNHk4HlWFsOr6aKE2zvsw0MuIgwCIPy6utIco14y7Ju91duEh8A","authorizedSince":1649729878532,"connectedSince":1649729873021,"returnRateLimits":false,"serverTime":1649729878630,"userDataStream":false}}"#).unwrap();
            resp_json["id"] = id.into();

            let raw_data = resp_json.get("result").or_else(|| resp_json.get("response")).expect("no response in JSON");
            let expected_data: Box<models::SessionLogonResponseResult> = serde_json::from_value(raw_data.clone()).expect("should parse raw response");
            let empty_array = Value::Array(vec![]);
            let raw_rate_limits = resp_json.get("rateLimits").unwrap_or(&empty_array);
            let expected_rate_limits: Option<Vec<WebsocketApiRateLimit>> =
                match raw_rate_limits.as_array() {
                    Some(arr) if arr.is_empty() => None,
                    Some(_) => Some(serde_json::from_value(raw_rate_limits.clone()).expect("should parse rateLimits array")),
                    None => None,
                };

            WebsocketHandler::on_message(&*ws_api, resp_json.to_string(), conn.clone()).await;

            let response = timeout(Duration::from_secs(1), handle).await.expect("task done").expect("no panic").expect("no error");
let response = response.into_iter().next().expect("should have response");

            let response_rate_limits = response.rate_limits.clone();
            let response_data = response.data().expect("deserialize data");

            assert_eq!(response_rate_limits, expected_rate_limits);
            assert_eq!(response_data, expected_data);
        });
    }

    #[test]
    fn session_logon_error_response() {
        TOKIO_SHARED_RT.block_on(async {
            let (ws_api, conn, mut rx) = setup().await;
            let client = AuthApiClient::new(ws_api.clone());

            let handle = tokio::spawn(async move {
                let params = SessionLogonParams::builder().build().unwrap();
                client.session_logon(params).await
            });

            let sent = timeout(Duration::from_secs(1), rx.recv()).await.unwrap().unwrap();
            let Message::Text(text) = sent else { panic!() };
            let v: Value = serde_json::from_str(&text).unwrap();
            let id = v["id"].as_str().unwrap().to_string();

            let resp_json = json!({
                "id": id,
                "status": 400,
                    "error": {
                        "code": -2010,
                        "msg": "Account has insufficient balance for requested action.",
                    },
                    "rateLimits": [
                        {
                            "rateLimitType": "ORDERS",
                            "interval": "SECOND",
                            "intervalNum": 10,
                            "limit": 50,
                            "count": 13
                        },
                    ],
            });
            WebsocketHandler::on_message(&*ws_api, resp_json.to_string(), conn.clone()).await;

            let join = timeout(Duration::from_secs(1), handle).await.unwrap();
            match join {
                Ok(Err(e)) => {
                    let msg = e.to_string();
                    assert!(
                        msg.contains("Server‐side response error (code -2010): Account has insufficient balance for requested action."),
                        "Expected error msg to contain server error, got: {msg}"
                    );
                }
                Ok(Ok(_)) => panic!("Expected error"),
                Err(_) => panic!("Task panicked"),
            }
        });
    }

    #[test]
    fn session_logon_request_timeout() {
        TOKIO_SHARED_RT.block_on(async {
            let (ws_api, _conn, mut rx) = setup().await;
            let client = AuthApiClient::new(ws_api.clone());

            let handle = spawn(async move {
                let params = SessionLogonParams::builder().build().unwrap();
                client.session_logon(params).await
            });

            let sent = timeout(Duration::from_secs(1), rx.recv())
                .await
                .expect("send should occur")
                .expect("channel closed");
            let Message::Text(text) = sent else {
                panic!("expected Message Text")
            };

            let _: Value = serde_json::from_str(&text).unwrap();

            let result = handle.await.expect("task completed");
            match result {
                Err(e) => {
                    if let Some(inner) = e.downcast_ref::<WebsocketError>() {
                        assert!(matches!(inner, WebsocketError::Timeout));
                    } else {
                        panic!("Unexpected error type: {:?}", e);
                    }
                }
                Ok(_) => panic!("Expected timeout error"),
            }
        });
    }

    #[test]
    fn session_logout_success() {
        TOKIO_SHARED_RT.block_on(async {
            let (ws_api, conn, mut rx) = setup().await;
            let client = AuthApiClient::new(ws_api.clone());

            let handle = spawn(async move {
                let params = SessionLogoutParams::builder().build().unwrap();
                client.session_logout(params).await
            });

            let sent = timeout(Duration::from_secs(1), rx.recv()).await.expect("send should occur").expect("channel closed");
            let Message::Text(text) = sent else { panic!() };
            let v: Value = serde_json::from_str(&text).unwrap();
            let id = v["id"].as_str().unwrap();
            assert_eq!(v["method"], "/session.logout".trim_start_matches('/'));

            let mut resp_json: Value = serde_json::from_str(r#"{"id":"c174a2b1-3f51-4580-b200-8528bd237cb7","status":200,"result":{"apiKey":"CAvIjXy3F44yW6Pou5k8Dy1swsYDWJZLeoK2r8G4cFDnE9nosRppc2eKc1T8TRTQ","authorizedSince":1649729878532,"connectedSince":1649729873021,"returnRateLimits":false,"serverTime":1649730611671,"userDataStream":false}}"#).unwrap();
            resp_json["id"] = id.into();

            let raw_data = resp_json.get("result").or_else(|| resp_json.get("response")).expect("no response in JSON");
            let expected_data: Box<models::SessionLogoutResponseResult> = serde_json::from_value(raw_data.clone()).expect("should parse raw response");
            let empty_array = Value::Array(vec![]);
            let raw_rate_limits = resp_json.get("rateLimits").unwrap_or(&empty_array);
            let expected_rate_limits: Option<Vec<WebsocketApiRateLimit>> =
                match raw_rate_limits.as_array() {
                    Some(arr) if arr.is_empty() => None,
                    Some(_) => Some(serde_json::from_value(raw_rate_limits.clone()).expect("should parse rateLimits array")),
                    None => None,
                };

            WebsocketHandler::on_message(&*ws_api, resp_json.to_string(), conn.clone()).await;

            let response = timeout(Duration::from_secs(1), handle).await.expect("task done").expect("no panic").expect("no error");
let response = response.into_iter().next().expect("should have response");

            let response_rate_limits = response.rate_limits.clone();
            let response_data = response.data().expect("deserialize data");

            assert_eq!(response_rate_limits, expected_rate_limits);
            assert_eq!(response_data, expected_data);
        });
    }

    #[test]
    fn session_logout_error_response() {
        TOKIO_SHARED_RT.block_on(async {
            let (ws_api, conn, mut rx) = setup().await;
            let client = AuthApiClient::new(ws_api.clone());

            let handle = tokio::spawn(async move {
                let params = SessionLogoutParams::builder().build().unwrap();
                client.session_logout(params).await
            });

            let sent = timeout(Duration::from_secs(1), rx.recv()).await.unwrap().unwrap();
            let Message::Text(text) = sent else { panic!() };
            let v: Value = serde_json::from_str(&text).unwrap();
            let id = v["id"].as_str().unwrap().to_string();

            let resp_json = json!({
                "id": id,
                "status": 400,
                    "error": {
                        "code": -2010,
                        "msg": "Account has insufficient balance for requested action.",
                    },
                    "rateLimits": [
                        {
                            "rateLimitType": "ORDERS",
                            "interval": "SECOND",
                            "intervalNum": 10,
                            "limit": 50,
                            "count": 13
                        },
                    ],
            });
            WebsocketHandler::on_message(&*ws_api, resp_json.to_string(), conn.clone()).await;

            let join = timeout(Duration::from_secs(1), handle).await.unwrap();
            match join {
                Ok(Err(e)) => {
                    let msg = e.to_string();
                    assert!(
                        msg.contains("Server‐side response error (code -2010): Account has insufficient balance for requested action."),
                        "Expected error msg to contain server error, got: {msg}"
                    );
                }
                Ok(Ok(_)) => panic!("Expected error"),
                Err(_) => panic!("Task panicked"),
            }
        });
    }

    #[test]
    fn session_logout_request_timeout() {
        TOKIO_SHARED_RT.block_on(async {
            let (ws_api, _conn, mut rx) = setup().await;
            let client = AuthApiClient::new(ws_api.clone());

            let handle = spawn(async move {
                let params = SessionLogoutParams::builder().build().unwrap();
                client.session_logout(params).await
            });

            let sent = timeout(Duration::from_secs(1), rx.recv())
                .await
                .expect("send should occur")
                .expect("channel closed");
            let Message::Text(text) = sent else {
                panic!("expected Message Text")
            };

            let _: Value = serde_json::from_str(&text).unwrap();

            let result = handle.await.expect("task completed");
            match result {
                Err(e) => {
                    if let Some(inner) = e.downcast_ref::<WebsocketError>() {
                        assert!(matches!(inner, WebsocketError::Timeout));
                    } else {
                        panic!("Unexpected error type: {:?}", e);
                    }
                }
                Ok(_) => panic!("Expected timeout error"),
            }
        });
    }

    #[test]
    fn session_status_success() {
        TOKIO_SHARED_RT.block_on(async {
            let (ws_api, conn, mut rx) = setup().await;
            let client = AuthApiClient::new(ws_api.clone());

            let handle = spawn(async move {
                let params = SessionStatusParams::builder().build().unwrap();
                client.session_status(params).await
            });

            let sent = timeout(Duration::from_secs(1), rx.recv()).await.expect("send should occur").expect("channel closed");
            let Message::Text(text) = sent else { panic!() };
            let v: Value = serde_json::from_str(&text).unwrap();
            let id = v["id"].as_str().unwrap();
            assert_eq!(v["method"], "/session.status".trim_start_matches('/'));

            let mut resp_json: Value = serde_json::from_str(r#"{"id":"b50c16cd-62c9-4e29-89e4-37f10111f5bf","status":200,"result":{"apiKey":"vmPUZE6mv9SD5VNHk4HlWFsOr6aKE2zvsw0MuIgwCIPy6utIco14y7Ju91duEh8A","authorizedSince":1649729878532,"connectedSince":1649729873021,"returnRateLimits":false,"serverTime":1649730611671,"userDataStream":true}}"#).unwrap();
            resp_json["id"] = id.into();

            let raw_data = resp_json.get("result").or_else(|| resp_json.get("response")).expect("no response in JSON");
            let expected_data: Box<models::SessionStatusResponseResult> = serde_json::from_value(raw_data.clone()).expect("should parse raw response");
            let empty_array = Value::Array(vec![]);
            let raw_rate_limits = resp_json.get("rateLimits").unwrap_or(&empty_array);
            let expected_rate_limits: Option<Vec<WebsocketApiRateLimit>> =
                match raw_rate_limits.as_array() {
                    Some(arr) if arr.is_empty() => None,
                    Some(_) => Some(serde_json::from_value(raw_rate_limits.clone()).expect("should parse rateLimits array")),
                    None => None,
                };

            WebsocketHandler::on_message(&*ws_api, resp_json.to_string(), conn.clone()).await;

            let response = timeout(Duration::from_secs(1), handle).await.expect("task done").expect("no panic").expect("no error");


            let response_rate_limits = response.rate_limits.clone();
            let response_data = response.data().expect("deserialize data");

            assert_eq!(response_rate_limits, expected_rate_limits);
            assert_eq!(response_data, expected_data);
        });
    }

    #[test]
    fn session_status_error_response() {
        TOKIO_SHARED_RT.block_on(async {
            let (ws_api, conn, mut rx) = setup().await;
            let client = AuthApiClient::new(ws_api.clone());

            let handle = tokio::spawn(async move {
                let params = SessionStatusParams::builder().build().unwrap();
                client.session_status(params).await
            });

            let sent = timeout(Duration::from_secs(1), rx.recv()).await.unwrap().unwrap();
            let Message::Text(text) = sent else { panic!() };
            let v: Value = serde_json::from_str(&text).unwrap();
            let id = v["id"].as_str().unwrap().to_string();

            let resp_json = json!({
                "id": id,
                "status": 400,
                    "error": {
                        "code": -2010,
                        "msg": "Account has insufficient balance for requested action.",
                    },
                    "rateLimits": [
                        {
                            "rateLimitType": "ORDERS",
                            "interval": "SECOND",
                            "intervalNum": 10,
                            "limit": 50,
                            "count": 13
                        },
                    ],
            });
            WebsocketHandler::on_message(&*ws_api, resp_json.to_string(), conn.clone()).await;

            let join = timeout(Duration::from_secs(1), handle).await.unwrap();
            match join {
                Ok(Err(e)) => {
                    let msg = e.to_string();
                    assert!(
                        msg.contains("Server‐side response error (code -2010): Account has insufficient balance for requested action."),
                        "Expected error msg to contain server error, got: {msg}"
                    );
                }
                Ok(Ok(_)) => panic!("Expected error"),
                Err(_) => panic!("Task panicked"),
            }
        });
    }

    #[test]
    fn session_status_request_timeout() {
        TOKIO_SHARED_RT.block_on(async {
            let (ws_api, _conn, mut rx) = setup().await;
            let client = AuthApiClient::new(ws_api.clone());

            let handle = spawn(async move {
                let params = SessionStatusParams::builder().build().unwrap();
                client.session_status(params).await
            });

            let sent = timeout(Duration::from_secs(1), rx.recv())
                .await
                .expect("send should occur")
                .expect("channel closed");
            let Message::Text(text) = sent else {
                panic!("expected Message Text")
            };

            let _: Value = serde_json::from_str(&text).unwrap();

            let result = handle.await.expect("task completed");
            match result {
                Err(e) => {
                    if let Some(inner) = e.downcast_ref::<WebsocketError>() {
                        assert!(matches!(inner, WebsocketError::Timeout));
                    } else {
                        panic!("Unexpected error type: {:?}", e);
                    }
                }
                Ok(_) => panic!("Expected timeout error"),
            }
        });
    }
}
