/*
 * Mithril
 *
 * Mithril Compute API
 *
 * The version of the OpenAPI document: 1.0.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 typed errors of method [`cancel_bid_v2_spot_bids_bid_fid_delete`]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum CancelBidV2SpotBidsBidFidDeleteError {
    Status422(models::HttpValidationError),
    UnknownValue(serde_json::Value),
}

/// struct for typed errors of method [`create_bid_v2_spot_bids_post`]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum CreateBidV2SpotBidsPostError {
    Status422(models::HttpValidationError),
    UnknownValue(serde_json::Value),
}

/// struct for typed errors of method [`get_auctions_v2_spot_availability_get`]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum GetAuctionsV2SpotAvailabilityGetError {
    UnknownValue(serde_json::Value),
}

/// struct for typed errors of method [`get_bid_history_v2_spot_bids_bid_fid_history_get`]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum GetBidHistoryV2SpotBidsBidFidHistoryGetError {
    Status422(models::HttpValidationError),
    UnknownValue(serde_json::Value),
}

/// struct for typed errors of method [`get_bid_status_v2_spot_bids_bid_fid_status_get`]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum GetBidStatusV2SpotBidsBidFidStatusGetError {
    Status422(models::HttpValidationError),
    UnknownValue(serde_json::Value),
}

/// struct for typed errors of method [`get_bid_v2_spot_bids_bid_fid_get`]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum GetBidV2SpotBidsBidFidGetError {
    Status422(models::HttpValidationError),
    UnknownValue(serde_json::Value),
}

/// struct for typed errors of method [`get_bids_v2_spot_bids_get`]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum GetBidsV2SpotBidsGetError {
    Status422(models::HttpValidationError),
    UnknownValue(serde_json::Value),
}

/// struct for typed errors of method [`update_bid_v2_spot_bids_bid_fid_patch`]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum UpdateBidV2SpotBidsBidFidPatchError {
    Status422(models::HttpValidationError),
    UnknownValue(serde_json::Value),
}

/// Cancel a Spot bid
pub async fn cancel_bid_v2_spot_bids_bid_fid_delete(
    configuration: &configuration::Configuration,
    bid_fid: &str,
) -> Result<(), Error<CancelBidV2SpotBidsBidFidDeleteError>> {
    // add a prefix to parameters to efficiently prevent name collisions
    let p_path_bid_fid = bid_fid;

    let uri_str = format!(
        "{}/v2/spot/bids/{bid_fid}",
        configuration.base_path,
        bid_fid = crate::apis::urlencode(p_path_bid_fid)
    );
    let mut req_builder = configuration
        .client
        .request(reqwest::Method::DELETE, &uri_str);

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

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

    let status = resp.status();

    if !status.is_client_error() && !status.is_server_error() {
        Ok(())
    } else {
        let content = resp.text().await?;
        let entity: Option<CancelBidV2SpotBidsBidFidDeleteError> =
            serde_json::from_str(&content).ok();
        Err(Error::ResponseError(ResponseContent {
            status,
            content,
            entity,
        }))
    }
}

/// Place a new Spot bid
pub async fn create_bid_v2_spot_bids_post(
    configuration: &configuration::Configuration,
    create_bid_request: models::CreateBidRequest,
) -> Result<models::BidModel, Error<CreateBidV2SpotBidsPostError>> {
    // add a prefix to parameters to efficiently prevent name collisions
    let p_body_create_bid_request = create_bid_request;

    let uri_str = format!("{}/v2/spot/bids", 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());
    }
    if let Some(ref token) = configuration.bearer_access_token {
        req_builder = req_builder.bearer_auth(token.to_owned());
    };
    req_builder = req_builder.json(&p_body_create_bid_request);

    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 => Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::BidModel`"))),
            ContentType::Unsupported(unknown_type) => Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::BidModel`")))),
        }
    } else {
        let content = resp.text().await?;
        let entity: Option<CreateBidV2SpotBidsPostError> = serde_json::from_str(&content).ok();
        Err(Error::ResponseError(ResponseContent {
            status,
            content,
            entity,
        }))
    }
}

/// Get the Spot availability across all regions.
pub async fn get_auctions_v2_spot_availability_get(
    configuration: &configuration::Configuration,
) -> Result<Vec<models::AuctionModel>, Error<GetAuctionsV2SpotAvailabilityGetError>> {
    let uri_str = format!("{}/v2/spot/availability", configuration.base_path);
    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());
    }
    if let Some(ref token) = configuration.bearer_access_token {
        req_builder = req_builder.bearer_auth(token.to_owned());
    };

    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 => Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `Vec&lt;models::AuctionModel&gt;`"))),
            ContentType::Unsupported(unknown_type) => Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `Vec&lt;models::AuctionModel&gt;`")))),
        }
    } else {
        let content = resp.text().await?;
        let entity: Option<GetAuctionsV2SpotAvailabilityGetError> =
            serde_json::from_str(&content).ok();
        Err(Error::ResponseError(ResponseContent {
            status,
            content,
            entity,
        }))
    }
}

/// Get the history of events for a Spot bid.  Returns a list of historical events including: - placing the bid - pausing the bid - resuming the bid - terminating the bid - changes to the limit price
pub async fn get_bid_history_v2_spot_bids_bid_fid_history_get(
    configuration: &configuration::Configuration,
    bid_fid: &str,
) -> Result<models::BidHistoryResponse, Error<GetBidHistoryV2SpotBidsBidFidHistoryGetError>> {
    // add a prefix to parameters to efficiently prevent name collisions
    let p_path_bid_fid = bid_fid;

    let uri_str = format!(
        "{}/v2/spot/bids/{bid_fid}/history",
        configuration.base_path,
        bid_fid = crate::apis::urlencode(p_path_bid_fid)
    );
    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());
    }
    if let Some(ref token) = configuration.bearer_access_token {
        req_builder = req_builder.bearer_auth(token.to_owned());
    };

    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 => Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::BidHistoryResponse`"))),
            ContentType::Unsupported(unknown_type) => Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::BidHistoryResponse`")))),
        }
    } else {
        let content = resp.text().await?;
        let entity: Option<GetBidHistoryV2SpotBidsBidFidHistoryGetError> =
            serde_json::from_str(&content).ok();
        Err(Error::ResponseError(ResponseContent {
            status,
            content,
            entity,
        }))
    }
}

/// Get detailed status of a Spot bid.  Returns a detailed status that includes instance-level status information. The status can be one of: Open, Allocated, Preempting, Terminated, Paused, Relocating.  \"Relocating\" indicates that part of the order is being relocated.
pub async fn get_bid_status_v2_spot_bids_bid_fid_status_get(
    configuration: &configuration::Configuration,
    bid_fid: &str,
) -> Result<models::BidStatusResponse, Error<GetBidStatusV2SpotBidsBidFidStatusGetError>> {
    // add a prefix to parameters to efficiently prevent name collisions
    let p_path_bid_fid = bid_fid;

    let uri_str = format!(
        "{}/v2/spot/bids/{bid_fid}/status",
        configuration.base_path,
        bid_fid = crate::apis::urlencode(p_path_bid_fid)
    );
    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());
    }
    if let Some(ref token) = configuration.bearer_access_token {
        req_builder = req_builder.bearer_auth(token.to_owned());
    };

    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 => Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::BidStatusResponse`"))),
            ContentType::Unsupported(unknown_type) => Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::BidStatusResponse`")))),
        }
    } else {
        let content = resp.text().await?;
        let entity: Option<GetBidStatusV2SpotBidsBidFidStatusGetError> =
            serde_json::from_str(&content).ok();
        Err(Error::ResponseError(ResponseContent {
            status,
            content,
            entity,
        }))
    }
}

/// Get a single Spot bid by FID
pub async fn get_bid_v2_spot_bids_bid_fid_get(
    configuration: &configuration::Configuration,
    bid_fid: &str,
) -> Result<models::BidModel, Error<GetBidV2SpotBidsBidFidGetError>> {
    // add a prefix to parameters to efficiently prevent name collisions
    let p_path_bid_fid = bid_fid;

    let uri_str = format!(
        "{}/v2/spot/bids/{bid_fid}",
        configuration.base_path,
        bid_fid = crate::apis::urlencode(p_path_bid_fid)
    );
    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());
    }
    if let Some(ref token) = configuration.bearer_access_token {
        req_builder = req_builder.bearer_auth(token.to_owned());
    };

    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 => Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::BidModel`"))),
            ContentType::Unsupported(unknown_type) => Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::BidModel`")))),
        }
    } else {
        let content = resp.text().await?;
        let entity: Option<GetBidV2SpotBidsBidFidGetError> = serde_json::from_str(&content).ok();
        Err(Error::ResponseError(ResponseContent {
            status,
            content,
            entity,
        }))
    }
}

/// Get all Spot bids for a project, or all user's projects if not specified
pub async fn get_bids_v2_spot_bids_get(
    configuration: &configuration::Configuration,
    next_cursor: Option<serde_json::Value>,
    sort_by: Option<&str>,
    sort_dir: Option<models::SortDirection>,
    project: Option<&str>,
    instance_type: Option<&str>,
    region: Option<&str>,
    status: Option<&str>,
    name: Option<&str>,
    limit: Option<i32>,
) -> Result<models::GetBidsResponse, Error<GetBidsV2SpotBidsGetError>> {
    // add a prefix to parameters to efficiently prevent name collisions
    let p_query_next_cursor = next_cursor;
    let p_query_sort_by = sort_by;
    let p_query_sort_dir = sort_dir;
    let p_query_project = project;
    let p_query_instance_type = instance_type;
    let p_query_region = region;
    let p_query_status = status;
    let p_query_name = name;
    let p_query_limit = limit;

    let uri_str = format!("{}/v2/spot/bids", configuration.base_path);
    let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str);

    if let Some(ref param_value) = p_query_next_cursor {
        req_builder = req_builder.query(&[("next_cursor", &serde_json::to_string(param_value)?)]);
    }
    if let Some(ref param_value) = p_query_sort_by {
        req_builder = req_builder.query(&[("sort_by", &param_value.to_string())]);
    }
    if let Some(ref param_value) = p_query_sort_dir {
        req_builder = req_builder.query(&[("sort_dir", &param_value.to_string())]);
    }
    if let Some(ref param_value) = p_query_project {
        req_builder = req_builder.query(&[("project", &param_value.to_string())]);
    }
    if let Some(ref param_value) = p_query_instance_type {
        req_builder = req_builder.query(&[("instance_type", &param_value.to_string())]);
    }
    if let Some(ref param_value) = p_query_region {
        req_builder = req_builder.query(&[("region", &param_value.to_string())]);
    }
    if let Some(ref param_value) = p_query_status {
        req_builder = req_builder.query(&[("status", &param_value.to_string())]);
    }
    if let Some(ref param_value) = p_query_name {
        req_builder = req_builder.query(&[("name", &param_value.to_string())]);
    }
    if let Some(ref param_value) = p_query_limit {
        req_builder = req_builder.query(&[("limit", &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());
    }
    if let Some(ref token) = configuration.bearer_access_token {
        req_builder = req_builder.bearer_auth(token.to_owned());
    };

    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 => Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::GetBidsResponse`"))),
            ContentType::Unsupported(unknown_type) => Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::GetBidsResponse`")))),
        }
    } else {
        let content = resp.text().await?;
        let entity: Option<GetBidsV2SpotBidsGetError> = serde_json::from_str(&content).ok();
        Err(Error::ResponseError(ResponseContent {
            status,
            content,
            entity,
        }))
    }
}

/// Update the limit price of a Spot bid
pub async fn update_bid_v2_spot_bids_bid_fid_patch(
    configuration: &configuration::Configuration,
    bid_fid: &str,
    update_bid_request: models::UpdateBidRequest,
) -> Result<models::BidModel, Error<UpdateBidV2SpotBidsBidFidPatchError>> {
    // add a prefix to parameters to efficiently prevent name collisions
    let p_path_bid_fid = bid_fid;
    let p_body_update_bid_request = update_bid_request;

    let uri_str = format!(
        "{}/v2/spot/bids/{bid_fid}",
        configuration.base_path,
        bid_fid = crate::apis::urlencode(p_path_bid_fid)
    );
    let mut req_builder = configuration
        .client
        .request(reqwest::Method::PATCH, &uri_str);

    if let Some(ref user_agent) = configuration.user_agent {
        req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone());
    }
    if let Some(ref token) = configuration.bearer_access_token {
        req_builder = req_builder.bearer_auth(token.to_owned());
    };
    req_builder = req_builder.json(&p_body_update_bid_request);

    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 => Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::BidModel`"))),
            ContentType::Unsupported(unknown_type) => Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::BidModel`")))),
        }
    } else {
        let content = resp.text().await?;
        let entity: Option<UpdateBidV2SpotBidsBidFidPatchError> =
            serde_json::from_str(&content).ok();
        Err(Error::ResponseError(ResponseContent {
            status,
            content,
            entity,
        }))
    }
}
