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

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

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

/// Create a new API key
pub async fn create_api_key_v2_api_keys_post(
    configuration: &configuration::Configuration,
    create_api_key_request: models::CreateApiKeyRequest,
) -> Result<models::CreateApiKeyResponse, Error<CreateApiKeyV2ApiKeysPostError>> {
    // add a prefix to parameters to efficiently prevent name collisions
    let p_body_create_api_key_request = create_api_key_request;

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

/// Get all API keys registered to the user
pub async fn get_api_keys_v2_api_keys_get(
    configuration: &configuration::Configuration,
) -> Result<Vec<models::ApiKeyModel>, Error<GetApiKeysV2ApiKeysGetError>> {
    let uri_str = format!("{}/v2/api-keys", 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::ApiKeyModel&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::ApiKeyModel&gt;`")))),
        }
    } else {
        let content = resp.text().await?;
        let entity: Option<GetApiKeysV2ApiKeysGetError> = serde_json::from_str(&content).ok();
        Err(Error::ResponseError(ResponseContent {
            status,
            content,
            entity,
        }))
    }
}

/// Revoke an API key
pub async fn revoke_api_key_v2_api_keys_key_fid_delete(
    configuration: &configuration::Configuration,
    key_fid: &str,
) -> Result<(), Error<RevokeApiKeyV2ApiKeysKeyFidDeleteError>> {
    // add a prefix to parameters to efficiently prevent name collisions
    let p_path_key_fid = key_fid;

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