/*
 * 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 [`position_controller_get_active`]
#[derive(Clone, Debug, Default)]
pub struct PositionControllerGetActiveParams {
    /// Id representing the registered subaccount
    pub subaccount_id: String,
    /// Id of product to filter position by
    pub product_id: String,
}

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

/// struct for passing parameters to the method [`position_controller_list_by_subaccount_id`]
#[derive(Clone, Debug, Default)]
pub struct PositionControllerListBySubaccountIdParams {
    /// Id representing the registered subaccount
    pub subaccount_id: String,
    /// Direction to paginate through objects
    pub order: Option<String>,
    /// Limit the number of objects to return
    pub limit: Option<i32>,
    /// 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>>,
    /// Include or exclude open positions (i.e. non-zero size)
    pub open: Option<bool>,
    /// Order by field
    pub order_by: Option<String>,
    /// Filter by order fills created before timestamp exclusive (ms since Unix epoch)
    pub created_after: Option<i32>,
    /// Filter by order fills created before timestamp inclusive (ms since Unix epoch)
    pub created_before: Option<i32>,
    /// Side as either BUY (0) or SELL (1)
    pub side: Option<f64>,
    /// Filter by liquidated positions
    pub is_liquidated: Option<bool>,
}

/// struct for passing parameters to the method [`position_controller_list_fills_by_position_id`]
#[derive(Clone, Debug, Default)]
pub struct PositionControllerListFillsByPositionIdParams {
    /// Id of the position to filter fills by
    pub position_id: String,
    /// Direction to paginate through objects
    pub order: Option<String>,
    /// Limit the number of objects to return
    pub limit: Option<i32>,
    /// Pointer to the current object in pagination dataset
    pub cursor: Option<String>,
    /// Order by field
    pub order_by: Option<String>,
}

/// struct for passing parameters to the method [`position_controller_list_liquidations_by_subaccount_id`]
#[derive(Clone, Debug, Default)]
pub struct PositionControllerListLiquidationsBySubaccountIdParams {
    /// Direction to paginate through objects
    pub order: Option<String>,
    /// Limit the number of objects to return
    pub limit: Option<i32>,
    /// Pointer to the current object in pagination dataset
    pub cursor: Option<String>,
    /// Order by field
    pub order_by: Option<String>,
}

/// struct for typed errors of method [`position_controller_get_active`]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum PositionControllerGetActiveError {
    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 [`position_controller_get_by_id`]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum PositionControllerGetByIdError {
    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 [`position_controller_list_by_subaccount_id`]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum PositionControllerListBySubaccountIdError {
    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 [`position_controller_list_fills_by_position_id`]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum PositionControllerListFillsByPositionIdError {
    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 [`position_controller_list_liquidations_by_subaccount_id`]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum PositionControllerListLiquidationsBySubaccountIdError {
    Status400(models::BadRequestDto),
    Status401(models::UnauthorizedDto),
    Status403(models::ForbiddenDto),
    Status404(models::NotFoundDto),
    Status422(models::UnprocessableEntityDto),
    Status429(models::TooManyRequestsDto),
    Status500(),
    UnknownValue(serde_json::Value),
}

pub async fn position_controller_get_active(
    configuration: &configuration::Configuration,
    params: PositionControllerGetActiveParams,
) -> Result<models::PositionDto, Error<PositionControllerGetActiveError>> {
    let uri_str = format!("{}/v1/position/active", configuration.base_path);
    let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str);

    req_builder = req_builder.query(&[("subaccountId", &params.subaccount_id.to_string())]);
    req_builder = req_builder.query(&[("productId", &params.product_id.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::PositionDto`"))),
            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::PositionDto`")))),
        }
    } else {
        let content = resp.text().await?;
        let entity: Option<PositionControllerGetActiveError> = serde_json::from_str(&content).ok();
        Err(Error::ResponseError(ResponseContent {
            status,
            content,
            entity,
        }))
    }
}

pub async fn position_controller_get_by_id(
    configuration: &configuration::Configuration,
    params: PositionControllerGetByIdParams,
) -> Result<models::PositionDto, Error<PositionControllerGetByIdError>> {
    let uri_str = format!(
        "{}/v1/position/{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::PositionDto`"))),
            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::PositionDto`")))),
        }
    } else {
        let content = resp.text().await?;
        let entity: Option<PositionControllerGetByIdError> = serde_json::from_str(&content).ok();
        Err(Error::ResponseError(ResponseContent {
            status,
            content,
            entity,
        }))
    }
}

pub async fn position_controller_list_by_subaccount_id(
    configuration: &configuration::Configuration,
    params: PositionControllerListBySubaccountIdParams,
) -> Result<models::PageOfPositionDtos, Error<PositionControllerListBySubaccountIdError>> {
    let uri_str = format!("{}/v1/position", 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.open {
        req_builder = req_builder.query(&[("open", &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.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.is_liquidated {
        req_builder = req_builder.query(&[("isLiquidated", &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::PageOfPositionDtos`"))),
            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::PageOfPositionDtos`")))),
        }
    } else {
        let content = resp.text().await?;
        let entity: Option<PositionControllerListBySubaccountIdError> =
            serde_json::from_str(&content).ok();
        Err(Error::ResponseError(ResponseContent {
            status,
            content,
            entity,
        }))
    }
}

pub async fn position_controller_list_fills_by_position_id(
    configuration: &configuration::Configuration,
    params: PositionControllerListFillsByPositionIdParams,
) -> Result<models::PageOfPositionFillDtos, Error<PositionControllerListFillsByPositionIdError>> {
    let uri_str = format!("{}/v1/position/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(&[("positionId", &params.position_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::PageOfPositionFillDtos`"))),
            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::PageOfPositionFillDtos`")))),
        }
    } else {
        let content = resp.text().await?;
        let entity: Option<PositionControllerListFillsByPositionIdError> =
            serde_json::from_str(&content).ok();
        Err(Error::ResponseError(ResponseContent {
            status,
            content,
            entity,
        }))
    }
}

pub async fn position_controller_list_liquidations_by_subaccount_id(
    configuration: &configuration::Configuration,
    params: PositionControllerListLiquidationsBySubaccountIdParams,
) -> Result<
    models::PageOfPositionLiquidationsDto,
    Error<PositionControllerListLiquidationsBySubaccountIdError>,
> {
    let uri_str = format!("{}/v1/position/liquidation", 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())]);
    }
    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::PageOfPositionLiquidationsDto`"))),
            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::PageOfPositionLiquidationsDto`")))),
        }
    } else {
        let content = resp.text().await?;
        let entity: Option<PositionControllerListLiquidationsBySubaccountIdError> =
            serde_json::from_str(&content).ok();
        Err(Error::ResponseError(ResponseContent {
            status,
            content,
            entity,
        }))
    }
}
