/*
 * Tapis Pods Service
 *
 *  The Pods Service is a web service and distributed computing platform providing pods-as-a-service (PaaS). The service  implements a message broker and processor model that requests pods, alongside a health module to poll for pod data, including logs, status, and health. The primary use of this service is to have quick to deploy long-lived services based on Docker images that are exposed via HTTP or TCP endpoints listed by the API.  **The Pods service provides functionality for two types of pod solutions:**  * **Templated Pods** for run-as-is popular images. Neo4J is one example, the template manages TCP ports, user creation, and permissions.  * **Custom Pods** for arbitrary docker images with less functionality. In this case we will expose port 5000 and do nothing else.   The live-docs act as the most up-to-date API reference. Visit the [documentation for more information](https://tapis.readthedocs.io/en/latest/technical/pods.html).
 *
 * The version of the OpenAPI document: 26Q1.1
 * Contact: cicsupport@tacc.utexas.edu
 * Generated by: https://openapi-generator.tech
 */

use super::{ContentType, Error, configuration};
use crate::{apis::ResponseContent, models};
use reqwest;
use serde::{Deserialize, Serialize, de::Error as _};

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

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

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

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

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

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

/// Create a secret with inputted information.  25Q4 Feature: Pods Secrets allow secure injection of credentials into pods.  Notes: - This endpoint creates new secrets only. Returns 409 Conflict if secret_id already exists. - To update an existing secret, use PUT /pods/secrets/{secret_id}. - Secrets are stored securely in Tapis Security Kernel (SK). - Secret names are automatically namespaced: ``pods_{tenant}_user_{username}_{name}`` - Only initial ADMIN can use this secret in pods unless you grant permissions. - Use ``secret_map`` in pod definitions to inject as environment variables. - All secret operations are logged  Request Body Fields: - **secret_id** (required): Alphanumeric name with underscores/dashes allowed (max 100 chars) - **secret_value** (required): The actual secret value to store securely - **description** (optional): ASCII description (max 500 chars) - **scope** (optional): ``user`` (default) or ``pod`` - determines secret visibility - **pod_id** (optional): Required if scope is ``pod``, must be omitted if scope is ``user`` - **readable** (optional): ``true`` (default) or ``false`` - controls if value can be retrieved via API - **writable** (optional): ``true`` (default) or ``false`` - controls if value can be updated via PUT  Access Mode Combinations: - ``readable=true, writable=true`` (default): Full access - value can be read and updated - ``readable=true, writable=false``: Read-only - value can be read but not updated (write-once) - ``readable=false, writable=true``: Write-only - value can be updated but not read via API - ``readable=false, writable=false``: Locked - value cannot be read or updated, only used via pod injection  Note: Pod injection via ``secret_map`` always works regardless of ``readable`` setting.  Usage in Pods: After creating a secret, reference it in your pod's ``secret_map``; after that, reference it with ${} in the fields that support secrets::      {         \"secret_map\": {             \"DB_PASSWORD\": \"${secret:my_db_secret}\"         },         \"environment_variables\": {             \"DATABASE_URL\": \"postgres://user:${pods:secrets:DB_PASSWORD}@localhost/db\"         }     }  Returns new secret object (without the secret value).
pub async fn create_secret(
    configuration: &configuration::Configuration,
    new_secret: models::NewSecret,
) -> Result<models::SecretResponse, Error<CreateSecretError>> {
    // add a prefix to parameters to efficiently prevent name collisions
    let p_body_new_secret = new_secret;

    let uri_str = format!("{}/pods/secrets", 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());
    }
    req_builder = req_builder.json(&p_body_new_secret);

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

/// Delete a secret from both the database and Security Kernel (SK).  25Q4 Feature: Pods Secrets allow secure injection of credentials into pods.  Note: - Requires ADMIN permission on the secret (only the creator has this by default). - This operation is permanent and cannot be undone. - Pods currently using this secret will fail to start until the secret reference is removed or a new secret with the same name is created by the pod owner. - All delete operations are logged.  Returns the deleted secret name.
pub async fn delete_secret(
    configuration: &configuration::Configuration,
    secret_id: &str,
) -> Result<models::SecretDeleteResponse, Error<DeleteSecretError>> {
    // add a prefix to parameters to efficiently prevent name collisions
    let p_path_secret_id = secret_id;

    let uri_str = format!(
        "{}/pods/secrets/{secret_id}",
        configuration.base_path,
        secret_id = crate::apis::urlencode(p_path_secret_id)
    );
    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());
    }

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

/// Get secret metadata (not the secret value itself).  25Q4 Feature: Pods Secrets allow secure injection of credentials into pods.  Note: - Returns metadata only. Use GET /secrets/{name}/value to retrieve the actual value. - Requires READ permission on the secret.  Returns secret metadata.
pub async fn get_secret(
    configuration: &configuration::Configuration,
    secret_id: &str,
) -> Result<models::SecretResponse, Error<GetSecretError>> {
    // add a prefix to parameters to efficiently prevent name collisions
    let p_path_secret_id = secret_id;

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

/// Get the actual secret value from SK.  25Q4 Feature: Pods Secrets allow secure injection of credentials into pods.  Note: - Requires USER permission on the secret (higher than READ). - Secrets with ``readable=False`` cannot have their values retrieved via this endpoint. - Pod injection via ``secret_map`` always works regardless of ``readable`` setting. - This operation is logged.  Returns the secret value.
pub async fn get_secret_value(
    configuration: &configuration::Configuration,
    secret_id: &str,
) -> Result<models::SecretValueResponse, Error<GetSecretValueError>> {
    // add a prefix to parameters to efficiently prevent name collisions
    let p_path_secret_id = secret_id;

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

/// Get all secrets you have permission to access.  25Q4 Feature: Pods Secrets allow secure injection of credentials into pods.  Note: - Returns metadata only, not secret values (use GET /secrets/{name}/value). - Filter shows only secrets where you have READ+ permission.  Returns a list of secrets (without secret values).
pub async fn list_secrets(
    configuration: &configuration::Configuration,
) -> Result<models::SecretsResponse, Error<ListSecretsError>> {
    let uri_str = format!("{}/pods/secrets", 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());
    }

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

/// Update a secret's description and/or value.  25Q4 Feature: Pods Secrets allow secure injection of credentials into pods.  Note: - Requires USER permission on the secret. - Secrets with ``writable=False`` cannot have their values updated (write-once secrets). - Description updates are always allowed regardless of ``writable`` setting. - Updates are logged. - Pods using this secret will get the new value on next start/restart.  Returns updated secret metadata.
pub async fn update_secret(
    configuration: &configuration::Configuration,
    secret_id: &str,
    update_secret: models::UpdateSecret,
) -> Result<models::SecretResponse, Error<UpdateSecretError>> {
    // add a prefix to parameters to efficiently prevent name collisions
    let p_path_secret_id = secret_id;
    let p_body_update_secret = update_secret;

    let uri_str = format!(
        "{}/pods/secrets/{secret_id}",
        configuration.base_path,
        secret_id = crate::apis::urlencode(p_path_secret_id)
    );
    let mut req_builder = configuration.client.request(reqwest::Method::PUT, &uri_str);

    if let Some(ref user_agent) = configuration.user_agent {
        req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone());
    }
    req_builder = req_builder.json(&p_body_update_secret);

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