/*
 * Tapis Systems API
 *
 * The Tapis Systems API provides for management of Tapis Systems including permissions, credentials and Scheduler Profiles.
 *
 * 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 [`check_user_credential`]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum CheckUserCredentialError {
    Status400(models::RespBasic),
    Status403(models::RespBasic),
    Status404(models::RespBasic),
    Status500(models::RespBasic),
    UnknownValue(serde_json::Value),
}

/// struct for typed errors of method [`create_user_credential`]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum CreateUserCredentialError {
    Status400(models::RespBasic),
    Status403(models::RespBasic),
    Status500(models::RespBasic),
    UnknownValue(serde_json::Value),
}

/// struct for typed errors of method [`generate_globus_tokens`]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum GenerateGlobusTokensError {
    Status400(models::RespBasic),
    Status401(models::RespBasic),
    Status500(models::RespBasic),
    UnknownValue(serde_json::Value),
}

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

/// struct for typed errors of method [`get_user_credential`]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum GetUserCredentialError {
    Status400(models::RespBasic),
    Status403(models::RespBasic),
    Status404(models::RespBasic),
    Status500(models::RespBasic),
    UnknownValue(serde_json::Value),
}

/// struct for typed errors of method [`remove_user_credential`]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum RemoveUserCredentialError {
    Status400(models::RespBasic),
    Status403(models::RespBasic),
    Status500(models::RespBasic),
    UnknownValue(serde_json::Value),
}

/// Check user credentials by connecting to the system host. Not supported for all system types. Currently supported for LINUX and S3 type systems.  If the *effectiveUserId* for the system is dynamic (i.e. equal to *${apiUserId}*) then *{userName}* is interpreted as a Tapis user and a search is made for credentials associated with *{userName}*. Note that the Tapis user *{userName}* may have a mapping to a host *loginUser* in which case the *loginUser* will be used when verifying the credentials. Note that what we call the *Tapis user* comes from the username claim in the Tapis JWT.  If the *effectiveUserId* for the system is static (i.e. not *${apiUserId}*) then *{userName}* is interpreted as the login user to be used when accessing the host. Note that this would typically be the current *effectiveUserId* defined for the system, but that is not a requirement. This allows for registering and checking credentials for a login user prior to updating the system definition.  Operation is allowed if requester is the system owner or a tenant administrator. If the *effectiveUserId* for the system is dynamic (i.e. equal to *${apiUserId}*) then the operation is allowed if *{userName}* is the Tapis user making the request.  Desired authentication method may be specified using query parameter *authnMethod*. If not specified, then credentials for the system's default authentication method are verified.
pub async fn check_user_credential(
    configuration: &configuration::Configuration,
    system_id: &str,
    user_name: &str,
    authn_method: Option<&str>,
) -> Result<models::RespBasic, Error<CheckUserCredentialError>> {
    // add a prefix to parameters to efficiently prevent name collisions
    let p_path_system_id = system_id;
    let p_path_user_name = user_name;
    let p_query_authn_method = authn_method;

    let uri_str = format!(
        "{}/v3/systems/credential/{systemId}/user/{userName}/check",
        configuration.base_path,
        systemId = crate::apis::urlencode(p_path_system_id),
        userName = crate::apis::urlencode(p_path_user_name)
    );
    let mut req_builder = configuration
        .client
        .request(reqwest::Method::POST, &uri_str);

    if let Some(ref param_value) = p_query_authn_method {
        req_builder = req_builder.query(&[("authnMethod", &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 apikey) = configuration.api_key {
        let key = apikey.key.clone();
        let value = match apikey.prefix {
            Some(ref prefix) => format!("{} {}", prefix, key),
            None => key,
        };
        req_builder = req_builder.header("X-Tapis-Token", value);
    };

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

/// Create or update credentials in the Security Kernel for given system and target *userName* using a request body. Credentials for multiple authentication methods may be provided. Note that there is support for only one set of credentials per user per system. Updating credentials overwrites previously registered data.  The Systems service does not store the secrets in its database, they are persisted in the Security Kernel.  If the *effectiveUserId* for the system is dynamic (i.e. equal to *${apiUserId}*) then *{userName}* is interpreted as a Tapis user and the request body may contain the optional attribute *loginUser* which will be used to map the Tapis user to a username to be used when accessing the system. If the login user is not provided then there is no mapping and the Tapis user is always used when accessing the system. Note that what we call the *Tapis user* comes from the username claim in the Tapis JWT.  If the *effectiveUserId* for the system is static (i.e. not *${apiUserId}*) then *{userName}* is interpreted as the login user to be used when accessing the host. Please note that if there is a *loginUser* field in the request body, TAPIS will reject the request because the static effective user is always the login user.  Operation is allowed if requester is the system owner or a tenant administrator. If the *effectiveUserId* for the system is dynamic (i.e. equal to *${apiUserId}*) then the operation is allowed if *{userName}* is the Tapis user making the request.  Use query parameter *createTmsKeys=true* to have the service call a Trust Manager System (TMS) server to create and store an ssh keypair. Default is *false*. Please note that the following restrictions apply:   - Tapis installation for your site must be configured to support the Trust Manager System (TMS).   - The host for the system must have the sshd configuration set up to use TMS.   - The *effectiveUserId* must be dynamic.   - Mapping of user using *loginUser* is not supported.  By default credentials for LINUX and S3 type systems are verified. Use query parameter *skipCredentialCheck=true* to bypass initial credential validation.
pub async fn create_user_credential(
    configuration: &configuration::Configuration,
    system_id: &str,
    user_name: &str,
    req_update_credential: models::ReqUpdateCredential,
    create_tms_keys: Option<bool>,
    skip_credential_check: Option<bool>,
) -> Result<models::RespBasic, Error<CreateUserCredentialError>> {
    // add a prefix to parameters to efficiently prevent name collisions
    let p_path_system_id = system_id;
    let p_path_user_name = user_name;
    let p_body_req_update_credential = req_update_credential;
    let p_query_create_tms_keys = create_tms_keys;
    let p_query_skip_credential_check = skip_credential_check;

    let uri_str = format!(
        "{}/v3/systems/credential/{systemId}/user/{userName}",
        configuration.base_path,
        systemId = crate::apis::urlencode(p_path_system_id),
        userName = crate::apis::urlencode(p_path_user_name)
    );
    let mut req_builder = configuration
        .client
        .request(reqwest::Method::POST, &uri_str);

    if let Some(ref param_value) = p_query_create_tms_keys {
        req_builder = req_builder.query(&[("createTmsKeys", &param_value.to_string())]);
    }
    if let Some(ref param_value) = p_query_skip_credential_check {
        req_builder = req_builder.query(&[("skipCredentialCheck", &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 apikey) = configuration.api_key {
        let key = apikey.key.clone();
        let value = match apikey.prefix {
            Some(ref prefix) => format!("{} {}", prefix, key),
            None => key,
        };
        req_builder = req_builder.header("X-Tapis-Token", value);
    };
    req_builder = req_builder.json(&p_body_req_update_credential);

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

/// Use a Globus *Native App Authorization Code* and a Tapis session Id to generate a pair of access and refresh tokens. System must be of type GLOBUS. The Systems service will use the Tapis Security Kernel to store the tokens for the given system and user.  If the *effectiveUserId* for the system is dynamic (i.e. equal to *${apiUserId}*) then *{userName}* must be set to the Tapis user. Note that what we call the *Tapis user* comes from the username claim in the Tapis JWT.  If the *effectiveUserId* for the system is static (i.e. not *${apiUserId}*) then *{userName}* must be set to the static *effectiveUserId*.  The session Id is a Tapis Id that is used to track the oauth2 flow that is started when a call to the getGlobusAuthUrl endpoint is made. The authorization code, as per Globus documentation, is valid for 10 minutes. Please note that the Tapis installation for your site must be configured by the site administrator to support systems of type GLOBUS.
pub async fn generate_globus_tokens(
    configuration: &configuration::Configuration,
    system_id: &str,
    user_name: &str,
    auth_code: &str,
    session_id: &str,
) -> Result<models::RespBasic, Error<GenerateGlobusTokensError>> {
    // add a prefix to parameters to efficiently prevent name collisions
    let p_path_system_id = system_id;
    let p_path_user_name = user_name;
    let p_path_auth_code = auth_code;
    let p_path_session_id = session_id;

    let uri_str = format!(
        "{}/v3/systems/credential/{systemId}/user/{userName}/globus/tokens/{authCode}/{sessionId}",
        configuration.base_path,
        systemId = crate::apis::urlencode(p_path_system_id),
        userName = crate::apis::urlencode(p_path_user_name),
        authCode = crate::apis::urlencode(p_path_auth_code),
        sessionId = crate::apis::urlencode(p_path_session_id)
    );
    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 apikey) = configuration.api_key {
        let key = apikey.key.clone();
        let value = match apikey.prefix {
            Some(ref prefix) => format!("{} {}", prefix, key),
            None => key,
        };
        req_builder = req_builder.header("X-Tapis-Token", value);
    };

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

/// Retrieve a Globus URL + Session Id that can be used to generate an oauth2 authorization code associated with the given system. System must be of type GLOBUS. In Globus, the code is referred to as a *Native App Authorization Code*. The host property of the system is used as the Globus Endpoint Id or Globus Collection Id. Once a user has obtained an authorization code, the corresponding Systems endpoint for generating Globus tokens should be called to exchange the code + sessionId for a pair of access and refresh tokens. The session Id is a Tapis Id that is used to track the oauth2 flow that is started when this call is made. The authorization code, as per Globus documentation, is valid for 10 minutes. Please note that the Tapis installation for your site must be configured by the site administrator to support systems of type GLOBUS.
pub async fn get_globus_auth_url(
    configuration: &configuration::Configuration,
    system_id: &str,
) -> Result<models::RespGlobusAuthUrl, Error<GetGlobusAuthUrlError>> {
    // add a prefix to parameters to efficiently prevent name collisions
    let p_path_system_id = system_id;

    let uri_str = format!(
        "{}/v3/systems/credential/{systemId}/globus/authUrl",
        configuration.base_path,
        systemId = crate::apis::urlencode(p_path_system_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 apikey) = configuration.api_key {
        let key = apikey.key.clone();
        let value = match apikey.prefix {
            Some(ref prefix) => format!("{} {}", prefix, key),
            None => key,
        };
        req_builder = req_builder.header("X-Tapis-Token", value);
    };

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

/// Restricted. Only certain Tapis services authorized.  Retrieve credentials for given system, target *userName* and authentication method.  If the *effectiveUserId* for the system is dynamic (i.e. equal to *${apiUserId}*) then *{userName}* is interpreted as a Tapis user. Note that there may me a mapping of the Tapis user to a host *loginUser* and what we call the *Tapis user* comes from the username claim in the Tapis JWT.  If the *effectiveUserId* for the system is static (i.e. not *${apiUserId}*) then *{userName}* is interpreted as the host *loginUser* that is used when accessing the host.  Desired authentication method may be specified using query parameter *authnMethod*. If desired authentication method not specified then credentials for the system's default authentication method are returned.  The result includes the attribute *authnMethod* indicating the authentication method associated with the returned credentials.
pub async fn get_user_credential(
    configuration: &configuration::Configuration,
    system_id: &str,
    user_name: &str,
    authn_method: Option<&str>,
) -> Result<models::RespCredential, Error<GetUserCredentialError>> {
    // add a prefix to parameters to efficiently prevent name collisions
    let p_path_system_id = system_id;
    let p_path_user_name = user_name;
    let p_query_authn_method = authn_method;

    let uri_str = format!(
        "{}/v3/systems/credential/{systemId}/user/{userName}",
        configuration.base_path,
        systemId = crate::apis::urlencode(p_path_system_id),
        userName = crate::apis::urlencode(p_path_user_name)
    );
    let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str);

    if let Some(ref param_value) = p_query_authn_method {
        req_builder = req_builder.query(&[("authnMethod", &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 apikey) = configuration.api_key {
        let key = apikey.key.clone();
        let value = match apikey.prefix {
            Some(ref prefix) => format!("{} {}", prefix, key),
            None => key,
        };
        req_builder = req_builder.header("X-Tapis-Token", value);
    };

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

/// Remove credentials from the Security Kernel for given system and *target user*. Requester must be owner of the system.  Operation is allowed if requester is the system owner or a tenant administrator. If the *effectiveUserId* for the system is dynamic (i.e. equal to *${apiUserId}*) then the operation is allowed if *{userName}* is the Tapis user making the request.
pub async fn remove_user_credential(
    configuration: &configuration::Configuration,
    system_id: &str,
    user_name: &str,
) -> Result<models::RespBasic, Error<RemoveUserCredentialError>> {
    // add a prefix to parameters to efficiently prevent name collisions
    let p_path_system_id = system_id;
    let p_path_user_name = user_name;

    let uri_str = format!(
        "{}/v3/systems/credential/{systemId}/user/{userName}",
        configuration.base_path,
        systemId = crate::apis::urlencode(p_path_system_id),
        userName = crate::apis::urlencode(p_path_user_name)
    );
    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 apikey) = configuration.api_key {
        let key = apikey.key.clone();
        let value = match apikey.prefix {
            Some(ref prefix) => format!("{} {}", prefix, key),
            None => key,
        };
        req_builder = req_builder.header("X-Tapis-Token", value);
    };

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