/*
 * Artifact Keeper API
 *
 * REST API for Artifact Keeper, an open-source universal artifact registry. Covers user management, repositories, artifacts, search, security scanning, SBOM, dependency tracking, SSO, analytics, monitoring, telemetry, lifecycle policies, plugins, edge nodes, migration, and administration. Format-specific protocol endpoints (npm, PyPI, Maven, Docker/OCI, etc.) are not included; those follow their respective upstream specifications.
 *
 * The version of the OpenAPI document: 1.0.0-a2
 * 
 * Generated by: https://openapi-generator.tech
 */


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


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

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

/// struct for typed errors of method [`list_public_sso_providers`]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum ListPublicSsoProvidersError {
    Status429(),
    Status500(models::ErrorResponse),
    UnknownValue(serde_json::Value),
}

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

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

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

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


/// Exchanges a temporary SSO authorization code (received via redirect after OIDC or SAML authentication) for access and refresh tokens.
pub async fn exchange_sso_code(configuration: &configuration::Configuration, exchange_sso_code_request: models::ExchangeSsoCodeRequest) -> Result<models::SsoExchangeResponse, Error<ExchangeSsoCodeError>> {
    // add a prefix to parameters to efficiently prevent name collisions
    let p_exchange_sso_code_request = exchange_sso_code_request;

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

/// Authenticates a user against the specified LDAP directory and returns access and refresh tokens.
pub async fn ldap_login(configuration: &configuration::Configuration, id: &str, ldap_login_request: models::LdapLoginRequest) -> Result<models::TokenPair, Error<LdapLoginError>> {
    // add a prefix to parameters to efficiently prevent name collisions
    let p_id = id;
    let p_ldap_login_request = ldap_login_request;

    let uri_str = format!("{}/api/v1/auth/sso/ldap/{id}/login", configuration.base_path, id=crate::apis::urlencode(p_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());
    }
    req_builder = req_builder.json(&p_ldap_login_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 => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::TokenPair`"))),
            ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::TokenPair`")))),
        }
    } else {
        let content = resp.text().await?;
        let entity: Option<LdapLoginError> = serde_json::from_str(&content).ok();
        Err(Error::ResponseError(ResponseContent { status, content, entity }))
    }
}

/// Returns all enabled SSO providers available for authentication. This endpoint is public and does not require authentication.
pub async fn list_public_sso_providers(configuration: &configuration::Configuration, ) -> Result<Vec<models::SsoProviderInfo>, Error<ListPublicSsoProvidersError>> {

    let uri_str = format!("{}/api/v1/auth/sso/providers", 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 => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `Vec&lt;models::SsoProviderInfo&gt;`"))),
            ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `Vec&lt;models::SsoProviderInfo&gt;`")))),
        }
    } else {
        let content = resp.text().await?;
        let entity: Option<ListPublicSsoProvidersError> = serde_json::from_str(&content).ok();
        Err(Error::ResponseError(ResponseContent { status, content, entity }))
    }
}

/// Handles the OIDC authorization code callback from the identity provider. Exchanges the code for tokens and redirects the user to the application with a session code.
pub async fn oidc_callback(configuration: &configuration::Configuration, id: &str, code: &str, state: &str) -> Result<models::SsoRedirectResponse, Error<OidcCallbackError>> {
    // add a prefix to parameters to efficiently prevent name collisions
    let p_id = id;
    let p_code = code;
    let p_state = state;

    let uri_str = format!("{}/api/v1/auth/sso/oidc/{id}/callback", configuration.base_path, id=crate::apis::urlencode(p_id));
    let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str);

    req_builder = req_builder.query(&[("code", &p_code.to_string())]);
    req_builder = req_builder.query(&[("state", &p_state.to_string())]);
    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 => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::SsoRedirectResponse`"))),
            ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::SsoRedirectResponse`")))),
        }
    } else {
        let content = resp.text().await?;
        let entity: Option<OidcCallbackError> = serde_json::from_str(&content).ok();
        Err(Error::ResponseError(ResponseContent { status, content, entity }))
    }
}

/// Initiates the OIDC authorization code flow by redirecting the user to the identity provider's authorization endpoint.
pub async fn oidc_login(configuration: &configuration::Configuration, id: &str) -> Result<models::SsoRedirectResponse, Error<OidcLoginError>> {
    // add a prefix to parameters to efficiently prevent name collisions
    let p_id = id;

    let uri_str = format!("{}/api/v1/auth/sso/oidc/{id}/login", configuration.base_path, id=crate::apis::urlencode(p_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 => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::SsoRedirectResponse`"))),
            ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::SsoRedirectResponse`")))),
        }
    } else {
        let content = resp.text().await?;
        let entity: Option<OidcLoginError> = serde_json::from_str(&content).ok();
        Err(Error::ResponseError(ResponseContent { status, content, entity }))
    }
}

/// Handles the SAML response from the identity provider. Validates the assertion, creates or updates the user, and redirects to the application with a session code.
pub async fn saml_acs(configuration: &configuration::Configuration, id: &str, saml_response: &str, relay_state: Option<&str>) -> Result<models::SsoRedirectResponse, Error<SamlAcsError>> {
    // add a prefix to parameters to efficiently prevent name collisions
    let p_id = id;
    let p_saml_response = saml_response;
    let p_relay_state = relay_state;

    let uri_str = format!("{}/api/v1/auth/sso/saml/{id}/acs", configuration.base_path, id=crate::apis::urlencode(p_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());
    }
    let mut multipart_form_params = std::collections::HashMap::new();
    multipart_form_params.insert("SAMLResponse", p_saml_response.to_string());
    if let Some(param_value) = p_relay_state {
        multipart_form_params.insert("RelayState", param_value.to_string());
    }
    req_builder = req_builder.form(&multipart_form_params);

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

/// Initiates the SAML authentication flow by redirecting the user to the identity provider's SSO endpoint with an authentication request.
pub async fn saml_login(configuration: &configuration::Configuration, id: &str) -> Result<models::SsoRedirectResponse, Error<SamlLoginError>> {
    // add a prefix to parameters to efficiently prevent name collisions
    let p_id = id;

    let uri_str = format!("{}/api/v1/auth/sso/saml/{id}/login", configuration.base_path, id=crate::apis::urlencode(p_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 => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::SsoRedirectResponse`"))),
            ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::SsoRedirectResponse`")))),
        }
    } else {
        let content = resp.text().await?;
        let entity: Option<SamlLoginError> = serde_json::from_str(&content).ok();
        Err(Error::ResponseError(ResponseContent { status, content, entity }))
    }
}

