/*
 * Ethereal Exchange API
 *
 * Ethereal HTTP API for real-time trading, order management, and market data access.
 *
 * The version of the OpenAPI document: 0.1.0
 *
 * Generated by: https://openapi-generator.tech
 */

use super::{configuration, ContentType, Error};
use crate::{apis::ResponseContent, models};
use reqwest;
use serde::{de::Error as _, Deserialize, Serialize};

/// struct for passing parameters to the method [`order_controller_cancel`]
#[derive(Clone, Debug, Default)]
pub struct OrderControllerCancelParams {
    pub cancel_order_dto: models::CancelOrderDto,
}

/// struct for passing parameters to the method [`order_controller_dry_run`]
#[derive(Clone, Debug, Default)]
pub struct OrderControllerDryRunParams {
    pub submit_dry_order_dto: models::SubmitDryOrderDto,
}

/// struct for passing parameters to the method [`order_controller_get_by_id`]
#[derive(Clone, Debug, Default)]
pub struct OrderControllerGetByIdParams {
    pub id: String,
}

/// struct for passing parameters to the method [`order_controller_list_by_subaccount_id`]
#[derive(Clone, Debug, Default)]
pub struct OrderControllerListBySubaccountIdParams {
    /// Id of the subaccount to query for
    pub subaccount_id: String,
    /// Direction to paginate through objects
    pub order: Option<String>,
    /// Limit the number of objects to return
    pub limit: Option<f64>,
    /// Pointer to the current object in pagination dataset
    pub cursor: Option<String>,
    /// Client-generated order id to query for (either a valid UUID or alphanumeric string up to 32 characters)
    pub client_order_id: Option<String>,
    /// Array of product ids to filter for
    pub product_ids: Option<Vec<uuid::Uuid>>,
    /// Filter by orders created after timestamp exclusive (ms since Unix epoch)
    pub created_after: Option<f64>,
    /// Filter by orders created before timestamp inclusive (ms since Unix epoch)
    pub created_before: Option<f64>,
    /// Side of the order to filter for
    pub side: Option<f64>,
    /// Whether the order is a position close order
    pub close: Option<bool>,
    /// Array of StopTypes to filter by
    pub stop_types: Option<Vec<f64>>,
    /// Filter by orders that are working: NEW, FILLED_PARTIAL
    pub is_working: Option<bool>,
    /// Filter by orders that are pending
    pub is_pending: Option<bool>,
    /// Order by field
    pub order_by: Option<String>,
}

/// struct for passing parameters to the method [`order_controller_list_fills_by_subaccount_id`]
#[derive(Clone, Debug, Default)]
pub struct OrderControllerListFillsBySubaccountIdParams {
    /// Id of the subaccount to filter fills by
    pub subaccount_id: String,
    /// Direction to paginate through objects
    pub order: Option<String>,
    /// Limit the number of objects to return
    pub limit: Option<f64>,
    /// Pointer to the current object in pagination dataset
    pub cursor: Option<String>,
    /// Array of product ids to filter for
    pub product_ids: Option<Vec<uuid::Uuid>>,
    /// Filter by order fills created before timestamp exclusive (ms since Unix epoch)
    pub created_after: Option<f64>,
    /// Filter by order fills created before timestamp inclusive (ms since Unix epoch)
    pub created_before: Option<f64>,
    /// Side as either BUY (0) or SELL (1)
    pub side: Option<f64>,
    /// Order by field
    pub order_by: Option<String>,
    /// Explicitly include self trades (excluded by default)
    pub include_self_trades: Option<bool>,
}

/// struct for passing parameters to the method [`order_controller_list_trades`]
#[derive(Clone, Debug, Default)]
pub struct OrderControllerListTradesParams {
    /// Id of the product to filter trades by
    pub product_id: String,
    /// Direction to paginate through objects
    pub order: Option<String>,
    /// Limit the number of objects to return
    pub limit: Option<f64>,
    /// Pointer to the current object in pagination dataset
    pub cursor: Option<String>,
    /// Order by fields
    pub order_by: Option<String>,
}

/// struct for passing parameters to the method [`order_controller_submit`]
#[derive(Clone, Debug, Default)]
pub struct OrderControllerSubmitParams {
    pub submit_order_dto: models::SubmitOrderDto,
}

/// struct for typed errors of method [`order_controller_cancel`]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum OrderControllerCancelError {
    Status400(models::BadRequestDto),
    Status401(models::UnauthorizedDto),
    Status403(models::ForbiddenDto),
    Status404(models::NotFoundDto),
    Status422(models::UnprocessableEntityDto),
    Status429(models::TooManyRequestsDto),
    Status500(),
    UnknownValue(serde_json::Value),
}

/// struct for typed errors of method [`order_controller_dry_run`]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum OrderControllerDryRunError {
    Status400(models::BadRequestDto),
    Status401(models::UnauthorizedDto),
    Status403(models::ForbiddenDto),
    Status404(models::NotFoundDto),
    Status422(models::DryRunOrderFailedUnprocessableEntityDto),
    Status429(models::TooManyRequestsDto),
    Status500(),
    UnknownValue(serde_json::Value),
}

/// struct for typed errors of method [`order_controller_get_by_id`]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum OrderControllerGetByIdError {
    Status400(models::BadRequestDto),
    Status401(models::UnauthorizedDto),
    Status403(models::ForbiddenDto),
    Status404(models::NotFoundDto),
    Status422(models::UnprocessableEntityDto),
    Status429(models::TooManyRequestsDto),
    Status500(),
    UnknownValue(serde_json::Value),
}

/// struct for typed errors of method [`order_controller_list_by_subaccount_id`]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum OrderControllerListBySubaccountIdError {
    Status400(models::BadRequestDto),
    Status401(models::UnauthorizedDto),
    Status403(models::ForbiddenDto),
    Status404(models::NotFoundDto),
    Status422(models::UnprocessableEntityDto),
    Status429(models::TooManyRequestsDto),
    Status500(),
    UnknownValue(serde_json::Value),
}

/// struct for typed errors of method [`order_controller_list_fills_by_subaccount_id`]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum OrderControllerListFillsBySubaccountIdError {
    Status400(models::BadRequestDto),
    Status401(models::UnauthorizedDto),
    Status403(models::ForbiddenDto),
    Status404(models::NotFoundDto),
    Status422(models::UnprocessableEntityDto),
    Status429(models::TooManyRequestsDto),
    Status500(),
    UnknownValue(serde_json::Value),
}

/// struct for typed errors of method [`order_controller_list_trades`]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum OrderControllerListTradesError {
    Status400(models::BadRequestDto),
    Status401(models::UnauthorizedDto),
    Status403(models::ForbiddenDto),
    Status404(models::NotFoundDto),
    Status422(models::UnprocessableEntityDto),
    Status429(models::TooManyRequestsDto),
    Status500(),
    UnknownValue(serde_json::Value),
}

/// struct for typed errors of method [`order_controller_submit`]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum OrderControllerSubmitError {
    Status400(models::BadRequestDto),
    Status401(models::UnauthorizedDto),
    Status403(models::ForbiddenDto),
    Status404(models::NotFoundDto),
    Status422(models::SubmitOrderFailedDto),
    Status429(models::TooManyRequestsDto),
    Status500(),
    UnknownValue(serde_json::Value),
}

pub async fn order_controller_cancel(
    configuration: &configuration::Configuration,
    params: OrderControllerCancelParams,
) -> Result<models::ListOfCancelOrderResultDtos, Error<OrderControllerCancelError>> {
    let uri_str = format!("{}/v1/order/cancel", configuration.base_path);
    let mut req_builder = configuration
        .client
        .request(reqwest::Method::POST, &uri_str);

    if let Some(ref user_agent) = configuration.user_agent {
        req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone());
    }
    req_builder = req_builder.json(&params.cancel_order_dto);

    let req = req_builder.build()?;
    let resp = configuration.client.execute(req).await?;

    let status = resp.status();
    let content_type = resp
        .headers()
        .get("content-type")
        .and_then(|v| v.to_str().ok())
        .unwrap_or("application/octet-stream");
    let content_type = super::ContentType::from(content_type);

    if !status.is_client_error() && !status.is_server_error() {
        let content = resp.text().await?;
        match content_type {
            ContentType::Json => serde_json::from_str(&content).map_err(Error::from),
            ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::ListOfCancelOrderResultDtos`"))),
            ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::ListOfCancelOrderResultDtos`")))),
        }
    } else {
        let content = resp.text().await?;
        let entity: Option<OrderControllerCancelError> = serde_json::from_str(&content).ok();
        Err(Error::ResponseError(ResponseContent {
            status,
            content,
            entity,
        }))
    }
}

pub async fn order_controller_dry_run(
    configuration: &configuration::Configuration,
    params: OrderControllerDryRunParams,
) -> Result<models::DryRunOrderCreatedDto, Error<OrderControllerDryRunError>> {
    let uri_str = format!("{}/v1/order/dry-run", configuration.base_path);
    let mut req_builder = configuration
        .client
        .request(reqwest::Method::POST, &uri_str);

    if let Some(ref user_agent) = configuration.user_agent {
        req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone());
    }
    req_builder = req_builder.json(&params.submit_dry_order_dto);

    let req = req_builder.build()?;
    let resp = configuration.client.execute(req).await?;

    let status = resp.status();
    let content_type = resp
        .headers()
        .get("content-type")
        .and_then(|v| v.to_str().ok())
        .unwrap_or("application/octet-stream");
    let content_type = super::ContentType::from(content_type);

    if !status.is_client_error() && !status.is_server_error() {
        let content = resp.text().await?;
        match content_type {
            ContentType::Json => serde_json::from_str(&content).map_err(Error::from),
            ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::DryRunOrderCreatedDto`"))),
            ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::DryRunOrderCreatedDto`")))),
        }
    } else {
        let content = resp.text().await?;
        let entity: Option<OrderControllerDryRunError> = serde_json::from_str(&content).ok();
        Err(Error::ResponseError(ResponseContent {
            status,
            content,
            entity,
        }))
    }
}

pub async fn order_controller_get_by_id(
    configuration: &configuration::Configuration,
    params: OrderControllerGetByIdParams,
) -> Result<models::OrderDto, Error<OrderControllerGetByIdError>> {
    let uri_str = format!(
        "{}/v1/order/{id}",
        configuration.base_path,
        id = crate::apis::urlencode(params.id)
    );
    let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str);

    if let Some(ref user_agent) = configuration.user_agent {
        req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone());
    }

    let req = req_builder.build()?;
    let resp = configuration.client.execute(req).await?;

    let status = resp.status();
    let content_type = resp
        .headers()
        .get("content-type")
        .and_then(|v| v.to_str().ok())
        .unwrap_or("application/octet-stream");
    let content_type = super::ContentType::from(content_type);

    if !status.is_client_error() && !status.is_server_error() {
        let content = resp.text().await?;
        match content_type {
            ContentType::Json => serde_json::from_str(&content).map_err(Error::from),
            ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::OrderDto`"))),
            ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::OrderDto`")))),
        }
    } else {
        let content = resp.text().await?;
        let entity: Option<OrderControllerGetByIdError> = serde_json::from_str(&content).ok();
        Err(Error::ResponseError(ResponseContent {
            status,
            content,
            entity,
        }))
    }
}

pub async fn order_controller_list_by_subaccount_id(
    configuration: &configuration::Configuration,
    params: OrderControllerListBySubaccountIdParams,
) -> Result<models::PageOfOrderDtos, Error<OrderControllerListBySubaccountIdError>> {
    let uri_str = format!("{}/v1/order", configuration.base_path);
    let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str);

    if let Some(ref param_value) = params.order {
        req_builder = req_builder.query(&[("order", &param_value.to_string())]);
    }
    if let Some(ref param_value) = params.limit {
        req_builder = req_builder.query(&[("limit", &param_value.to_string())]);
    }
    if let Some(ref param_value) = params.cursor {
        req_builder = req_builder.query(&[("cursor", &param_value.to_string())]);
    }
    req_builder = req_builder.query(&[("subaccountId", &params.subaccount_id.to_string())]);
    if let Some(ref param_value) = params.client_order_id {
        req_builder = req_builder.query(&[("clientOrderId", &param_value.to_string())]);
    }
    if let Some(ref param_value) = params.product_ids {
        req_builder = match "multi" {
            "multi" => req_builder.query(
                &param_value
                    .into_iter()
                    .map(|p| ("productIds".to_owned(), p.to_string()))
                    .collect::<Vec<(std::string::String, std::string::String)>>(),
            ),
            _ => req_builder.query(&[(
                "productIds",
                &param_value
                    .into_iter()
                    .map(|p| p.to_string())
                    .collect::<Vec<String>>()
                    .join(",")
                    .to_string(),
            )]),
        };
    }
    if let Some(ref param_value) = params.created_after {
        req_builder = req_builder.query(&[("createdAfter", &param_value.to_string())]);
    }
    if let Some(ref param_value) = params.created_before {
        req_builder = req_builder.query(&[("createdBefore", &param_value.to_string())]);
    }
    if let Some(ref param_value) = params.side {
        req_builder = req_builder.query(&[("side", &param_value.to_string())]);
    }
    if let Some(ref param_value) = params.close {
        req_builder = req_builder.query(&[("close", &param_value.to_string())]);
    }
    if let Some(ref param_value) = params.stop_types {
        req_builder = match "multi" {
            "multi" => req_builder.query(
                &param_value
                    .into_iter()
                    .map(|p| ("stopTypes".to_owned(), p.to_string()))
                    .collect::<Vec<(std::string::String, std::string::String)>>(),
            ),
            _ => req_builder.query(&[(
                "stopTypes",
                &param_value
                    .into_iter()
                    .map(|p| p.to_string())
                    .collect::<Vec<String>>()
                    .join(",")
                    .to_string(),
            )]),
        };
    }
    if let Some(ref param_value) = params.is_working {
        req_builder = req_builder.query(&[("isWorking", &param_value.to_string())]);
    }
    if let Some(ref param_value) = params.is_pending {
        req_builder = req_builder.query(&[("isPending", &param_value.to_string())]);
    }
    if let Some(ref param_value) = params.order_by {
        req_builder = req_builder.query(&[("orderBy", &param_value.to_string())]);
    }
    if let Some(ref user_agent) = configuration.user_agent {
        req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone());
    }

    let req = req_builder.build()?;
    let resp = configuration.client.execute(req).await?;

    let status = resp.status();
    let content_type = resp
        .headers()
        .get("content-type")
        .and_then(|v| v.to_str().ok())
        .unwrap_or("application/octet-stream");
    let content_type = super::ContentType::from(content_type);

    if !status.is_client_error() && !status.is_server_error() {
        let content = resp.text().await?;
        match content_type {
            ContentType::Json => serde_json::from_str(&content).map_err(Error::from),
            ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::PageOfOrderDtos`"))),
            ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::PageOfOrderDtos`")))),
        }
    } else {
        let content = resp.text().await?;
        let entity: Option<OrderControllerListBySubaccountIdError> =
            serde_json::from_str(&content).ok();
        Err(Error::ResponseError(ResponseContent {
            status,
            content,
            entity,
        }))
    }
}

pub async fn order_controller_list_fills_by_subaccount_id(
    configuration: &configuration::Configuration,
    params: OrderControllerListFillsBySubaccountIdParams,
) -> Result<models::PageOfOrderFillDtos, Error<OrderControllerListFillsBySubaccountIdError>> {
    let uri_str = format!("{}/v1/order/fill", configuration.base_path);
    let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str);

    if let Some(ref param_value) = params.order {
        req_builder = req_builder.query(&[("order", &param_value.to_string())]);
    }
    if let Some(ref param_value) = params.limit {
        req_builder = req_builder.query(&[("limit", &param_value.to_string())]);
    }
    if let Some(ref param_value) = params.cursor {
        req_builder = req_builder.query(&[("cursor", &param_value.to_string())]);
    }
    req_builder = req_builder.query(&[("subaccountId", &params.subaccount_id.to_string())]);
    if let Some(ref param_value) = params.product_ids {
        req_builder = match "multi" {
            "multi" => req_builder.query(
                &param_value
                    .into_iter()
                    .map(|p| ("productIds".to_owned(), p.to_string()))
                    .collect::<Vec<(std::string::String, std::string::String)>>(),
            ),
            _ => req_builder.query(&[(
                "productIds",
                &param_value
                    .into_iter()
                    .map(|p| p.to_string())
                    .collect::<Vec<String>>()
                    .join(",")
                    .to_string(),
            )]),
        };
    }
    if let Some(ref param_value) = params.created_after {
        req_builder = req_builder.query(&[("createdAfter", &param_value.to_string())]);
    }
    if let Some(ref param_value) = params.created_before {
        req_builder = req_builder.query(&[("createdBefore", &param_value.to_string())]);
    }
    if let Some(ref param_value) = params.side {
        req_builder = req_builder.query(&[("side", &param_value.to_string())]);
    }
    if let Some(ref param_value) = params.order_by {
        req_builder = req_builder.query(&[("orderBy", &param_value.to_string())]);
    }
    if let Some(ref param_value) = params.include_self_trades {
        req_builder = req_builder.query(&[("includeSelfTrades", &param_value.to_string())]);
    }
    if let Some(ref user_agent) = configuration.user_agent {
        req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone());
    }

    let req = req_builder.build()?;
    let resp = configuration.client.execute(req).await?;

    let status = resp.status();
    let content_type = resp
        .headers()
        .get("content-type")
        .and_then(|v| v.to_str().ok())
        .unwrap_or("application/octet-stream");
    let content_type = super::ContentType::from(content_type);

    if !status.is_client_error() && !status.is_server_error() {
        let content = resp.text().await?;
        match content_type {
            ContentType::Json => serde_json::from_str(&content).map_err(Error::from),
            ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::PageOfOrderFillDtos`"))),
            ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::PageOfOrderFillDtos`")))),
        }
    } else {
        let content = resp.text().await?;
        let entity: Option<OrderControllerListFillsBySubaccountIdError> =
            serde_json::from_str(&content).ok();
        Err(Error::ResponseError(ResponseContent {
            status,
            content,
            entity,
        }))
    }
}

pub async fn order_controller_list_trades(
    configuration: &configuration::Configuration,
    params: OrderControllerListTradesParams,
) -> Result<models::PageOfTradeDtos, Error<OrderControllerListTradesError>> {
    let uri_str = format!("{}/v1/order/trade", configuration.base_path);
    let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str);

    if let Some(ref param_value) = params.order {
        req_builder = req_builder.query(&[("order", &param_value.to_string())]);
    }
    if let Some(ref param_value) = params.limit {
        req_builder = req_builder.query(&[("limit", &param_value.to_string())]);
    }
    if let Some(ref param_value) = params.cursor {
        req_builder = req_builder.query(&[("cursor", &param_value.to_string())]);
    }
    req_builder = req_builder.query(&[("productId", &params.product_id.to_string())]);
    if let Some(ref param_value) = params.order_by {
        req_builder = req_builder.query(&[("orderBy", &param_value.to_string())]);
    }
    if let Some(ref user_agent) = configuration.user_agent {
        req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone());
    }

    let req = req_builder.build()?;
    let resp = configuration.client.execute(req).await?;

    let status = resp.status();
    let content_type = resp
        .headers()
        .get("content-type")
        .and_then(|v| v.to_str().ok())
        .unwrap_or("application/octet-stream");
    let content_type = super::ContentType::from(content_type);

    if !status.is_client_error() && !status.is_server_error() {
        let content = resp.text().await?;
        match content_type {
            ContentType::Json => serde_json::from_str(&content).map_err(Error::from),
            ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::PageOfTradeDtos`"))),
            ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::PageOfTradeDtos`")))),
        }
    } else {
        let content = resp.text().await?;
        let entity: Option<OrderControllerListTradesError> = serde_json::from_str(&content).ok();
        Err(Error::ResponseError(ResponseContent {
            status,
            content,
            entity,
        }))
    }
}

pub async fn order_controller_submit(
    configuration: &configuration::Configuration,
    params: OrderControllerSubmitParams,
) -> Result<models::SubmitOrderCreatedDto, Error<OrderControllerSubmitError>> {
    let uri_str = format!("{}/v1/order", configuration.base_path);
    let mut req_builder = configuration
        .client
        .request(reqwest::Method::POST, &uri_str);

    if let Some(ref user_agent) = configuration.user_agent {
        req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone());
    }
    req_builder = req_builder.json(&params.submit_order_dto);

    let req = req_builder.build()?;
    let resp = configuration.client.execute(req).await?;

    let status = resp.status();
    let content_type = resp
        .headers()
        .get("content-type")
        .and_then(|v| v.to_str().ok())
        .unwrap_or("application/octet-stream");
    let content_type = super::ContentType::from(content_type);

    if !status.is_client_error() && !status.is_server_error() {
        let content = resp.text().await?;
        match content_type {
            ContentType::Json => serde_json::from_str(&content).map_err(Error::from),
            ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::SubmitOrderCreatedDto`"))),
            ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::SubmitOrderCreatedDto`")))),
        }
    } else {
        let content = resp.text().await?;
        let entity: Option<OrderControllerSubmitError> = serde_json::from_str(&content).ok();
        Err(Error::ResponseError(ResponseContent {
            status,
            content,
            entity,
        }))
    }
}
