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

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

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

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

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

/// Create a new lifecycle script
pub async fn create_lifecycle_script_v2_lifecycle_scripts_post(
    configuration: &configuration::Configuration,
    create_lifecycle_script_request: models::CreateLifecycleScriptRequest,
) -> Result<models::LifecycleScriptModel, Error<CreateLifecycleScriptV2LifecycleScriptsPostError>> {
    // add a prefix to parameters to efficiently prevent name collisions
    let p_body_create_lifecycle_script_request = create_lifecycle_script_request;

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

pub async fn delete_lifecycle_script_v2_lifecycle_scripts_ls_fid_delete(
    configuration: &configuration::Configuration,
    ls_fid: &str,
) -> Result<(), Error<DeleteLifecycleScriptV2LifecycleScriptsLsFidDeleteError>> {
    // add a prefix to parameters to efficiently prevent name collisions
    let p_path_ls_fid = ls_fid;

    let uri_str = format!(
        "{}/v2/lifecycle-scripts/{ls_fid}",
        configuration.base_path,
        ls_fid = crate::apis::urlencode(p_path_ls_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<DeleteLifecycleScriptV2LifecycleScriptsLsFidDeleteError> =
            serde_json::from_str(&content).ok();
        Err(Error::ResponseError(ResponseContent {
            status,
            content,
            entity,
        }))
    }
}

pub async fn get_lifecycle_script_content_v2_lifecycle_scripts_ls_fid_content_get(
    configuration: &configuration::Configuration,
    ls_fid: &str,
) -> Result<serde_json::Value, Error<GetLifecycleScriptContentV2LifecycleScriptsLsFidContentGetError>>
{
    // add a prefix to parameters to efficiently prevent name collisions
    let p_path_ls_fid = ls_fid;

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

/// Get all lifecycle scripts visible to user in a project
pub async fn list_lifecycle_scripts_v2_lifecycle_scripts_get(
    configuration: &configuration::Configuration,
    project: &str,
    next_cursor: Option<serde_json::Value>,
    sort_by: Option<&str>,
    sort_dir: Option<models::SortDirection>,
    limit: Option<i32>,
) -> Result<
    models::ListLifecycleScriptsResponse,
    Error<ListLifecycleScriptsV2LifecycleScriptsGetError>,
> {
    // 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_limit = limit;

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

pub async fn update_lifecycle_script_v2_lifecycle_scripts_ls_fid_patch(
    configuration: &configuration::Configuration,
    ls_fid: &str,
    update_lifecycle_script_request: models::UpdateLifecycleScriptRequest,
) -> Result<
    models::LifecycleScriptModel,
    Error<UpdateLifecycleScriptV2LifecycleScriptsLsFidPatchError>,
> {
    // add a prefix to parameters to efficiently prevent name collisions
    let p_path_ls_fid = ls_fid;
    let p_body_update_lifecycle_script_request = update_lifecycle_script_request;

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