/*
 * 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 [`get_instance_status_v2_instances_instance_id_status_get`]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum GetInstanceStatusV2InstancesInstanceIdStatusGetError {
    Status422(models::HttpValidationError),
    UnknownValue(serde_json::Value),
}

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

/// Get the status of a specific instance by its ID
pub async fn get_instance_status_v2_instances_instance_id_status_get(
    configuration: &configuration::Configuration,
    instance_id: &str,
) -> Result<
    models::InstanceStatusResponse,
    Error<GetInstanceStatusV2InstancesInstanceIdStatusGetError>,
> {
    // add a prefix to parameters to efficiently prevent name collisions
    let p_path_instance_id = instance_id;

    let uri_str = format!(
        "{}/v2/instances/{instance_id}/status",
        configuration.base_path,
        instance_id = crate::apis::urlencode(p_path_instance_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());
    }
    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::InstanceStatusResponse`"))),
            ContentType::Unsupported(unknown_type) => Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::InstanceStatusResponse`")))),
        }
    } else {
        let content = resp.text().await?;
        let entity: Option<GetInstanceStatusV2InstancesInstanceIdStatusGetError> =
            serde_json::from_str(&content).ok();
        Err(Error::ResponseError(ResponseContent {
            status,
            content,
            entity,
        }))
    }
}

/// Get all instances for a project
pub async fn get_instances_v2_instances_get(
    configuration: &configuration::Configuration,
    project: &str,
    next_cursor: Option<serde_json::Value>,
    sort_by: Option<&str>,
    sort_dir: Option<models::SortDirection>,
    instance_type: Option<&str>,
    region: Option<&str>,
    status_in: Option<Vec<String>>,
    order_type_in: Option<Vec<String>>,
    bid_fid_in: Option<Vec<String>>,
    reservation_fid_in: Option<Vec<String>>,
    limit: Option<i32>,
) -> Result<models::GetInstancesResponse, Error<GetInstancesV2InstancesGetError>> {
    // add a prefix to parameters to efficiently prevent name collisions
    let p_query_project = project;
    let p_query_next_cursor = next_cursor;
    let p_query_sort_by = sort_by;
    let p_query_sort_dir = sort_dir;
    let p_query_instance_type = instance_type;
    let p_query_region = region;
    let p_query_status_in = status_in;
    let p_query_order_type_in = order_type_in;
    let p_query_bid_fid_in = bid_fid_in;
    let p_query_reservation_fid_in = reservation_fid_in;
    let p_query_limit = limit;

    let uri_str = format!("{}/v2/instances", 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())]);
    }
    req_builder = req_builder.query(&[("project", &p_query_project.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_in {
        req_builder = match "multi" {
            "multi" => req_builder.query(
                &param_value
                    .iter()
                    .map(|p| ("status_in".to_owned(), p.to_string()))
                    .collect::<Vec<(std::string::String, std::string::String)>>(),
            ),
            _ => req_builder.query(&[(
                "status_in",
                &param_value
                    .iter()
                    .map(|p| p.to_string())
                    .collect::<Vec<String>>()
                    .join(",")
                    .to_string(),
            )]),
        };
    }
    if let Some(ref param_value) = p_query_order_type_in {
        req_builder = match "multi" {
            "multi" => req_builder.query(
                &param_value
                    .iter()
                    .map(|p| ("order_type_in".to_owned(), p.to_string()))
                    .collect::<Vec<(std::string::String, std::string::String)>>(),
            ),
            _ => req_builder.query(&[(
                "order_type_in",
                &param_value
                    .iter()
                    .map(|p| p.to_string())
                    .collect::<Vec<String>>()
                    .join(",")
                    .to_string(),
            )]),
        };
    }
    if let Some(ref param_value) = p_query_bid_fid_in {
        req_builder = match "multi" {
            "multi" => req_builder.query(
                &param_value
                    .iter()
                    .map(|p| ("bid_fid_in".to_owned(), p.to_string()))
                    .collect::<Vec<(std::string::String, std::string::String)>>(),
            ),
            _ => req_builder.query(&[(
                "bid_fid_in",
                &param_value
                    .iter()
                    .map(|p| p.to_string())
                    .collect::<Vec<String>>()
                    .join(",")
                    .to_string(),
            )]),
        };
    }
    if let Some(ref param_value) = p_query_reservation_fid_in {
        req_builder = match "multi" {
            "multi" => req_builder.query(
                &param_value
                    .iter()
                    .map(|p| ("reservation_fid_in".to_owned(), p.to_string()))
                    .collect::<Vec<(std::string::String, std::string::String)>>(),
            ),
            _ => req_builder.query(&[(
                "reservation_fid_in",
                &param_value
                    .iter()
                    .map(|p| p.to_string())
                    .collect::<Vec<String>>()
                    .join(",")
                    .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::GetInstancesResponse`"))),
            ContentType::Unsupported(unknown_type) => Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::GetInstancesResponse`")))),
        }
    } else {
        let content = resp.text().await?;
        let entity: Option<GetInstancesV2InstancesGetError> = serde_json::from_str(&content).ok();
        Err(Error::ResponseError(ResponseContent {
            status,
            content,
            entity,
        }))
    }
}
