/*
 * doqium - service-auth REST API
 *
 * doqium - service-auth REST API
 *
 * The version of the OpenAPI document: 1.0
 *
 * Generated by: https://openapi-generator.tech
 */

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

/// struct for typed errors of method [`session_authenticate`]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum SessionAuthenticateError {
    Status401(models::ErrorModel),
    Status403(models::ErrorModel),
    Status404(models::ErrorModel),
    Status409(models::ErrorModel),
    Status429(models::ErrorModel),
    Status500(models::ErrorModel),
    UnknownValue(serde_json::Value),
}

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

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

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

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

/// struct for typed errors of method [`session_revoke_token_by_id`]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum SessionRevokeTokenByIdError {
    Status401(models::ErrorModel),
    Status403(models::ErrorModel),
    Status404(models::ErrorModel),
    Status429(models::ErrorModel),
    Status500(models::ErrorModel),
    UnknownValue(serde_json::Value),
}

/// Approve a pending session authentication request (requires user session)
pub async fn session_authenticate(
    configuration: &configuration::Configuration,
    request_id: &str,
) -> Result<models::SessionAuthenticate200Response, Error<SessionAuthenticateError>> {
    // add a prefix to parameters to efficiently prevent name collisions
    let p_path_request_id = request_id;

    let uri_str = format!(
        "{}/auth/v1/sessions/authenticate/{requestId}",
        configuration.base_path,
        requestId = crate::doqium_auth_client::apis::urlencode(p_path_request_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 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::SessionAuthenticate200Response`"))),
            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::SessionAuthenticate200Response`")))),
        }
    } else {
        let content = resp.text().await?;
        let entity: Option<SessionAuthenticateError> = serde_json::from_str(&content).ok();
        Err(Error::ResponseError(ResponseContent {
            status,
            content,
            entity,
        }))
    }
}

/// Render the authentication form for approving a session request (public endpoint, but authentication required to submit)
pub async fn session_get_form(
    configuration: &configuration::Configuration,
    request_id: &str,
) -> Result<String, Error<SessionGetFormError>> {
    // add a prefix to parameters to efficiently prevent name collisions
    let p_path_request_id = request_id;

    let uri_str = format!(
        "{}/auth/v1/sessions/authenticate/{requestId}",
        configuration.base_path,
        requestId = crate::doqium_auth_client::apis::urlencode(p_path_request_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 `String`"))),
            ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `String`")))),
        }
    } else {
        let content = resp.text().await?;
        let entity: Option<SessionGetFormError> = serde_json::from_str(&content).ok();
        Err(Error::ResponseError(ResponseContent {
            status,
            content,
            entity,
        }))
    }
}

/// Retrieve the JWT token for an authenticated session request
pub async fn session_get_token(
    configuration: &configuration::Configuration,
    request_id: &str,
) -> Result<models::SessionGetToken200Response, Error<SessionGetTokenError>> {
    // add a prefix to parameters to efficiently prevent name collisions
    let p_path_request_id = request_id;

    let uri_str = format!(
        "{}/auth/v1/sessions/token/{requestId}",
        configuration.base_path,
        requestId = crate::doqium_auth_client::apis::urlencode(p_path_request_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::SessionGetToken200Response`"))),
            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::SessionGetToken200Response`")))),
        }
    } else {
        let content = resp.text().await?;
        let entity: Option<SessionGetTokenError> = serde_json::from_str(&content).ok();
        Err(Error::ResponseError(ResponseContent {
            status,
            content,
            entity,
        }))
    }
}

/// Retrieve all active authentication tokens for the authenticated user
pub async fn session_list_tokens(
    configuration: &configuration::Configuration,
) -> Result<Vec<models::SessionListTokens200ResponseInner>, Error<SessionListTokensError>> {
    let uri_str = format!("{}/auth/v1/sessions/tokens", 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::SessionListTokens200ResponseInner&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::SessionListTokens200ResponseInner&gt;`")))),
        }
    } else {
        let content = resp.text().await?;
        let entity: Option<SessionListTokensError> = serde_json::from_str(&content).ok();
        Err(Error::ResponseError(ResponseContent {
            status,
            content,
            entity,
        }))
    }
}

/// Create a pending session authentication request
pub async fn session_request(
    configuration: &configuration::Configuration,
    session_request_request: models::SessionRequestRequest,
) -> Result<models::SessionRequest200Response, Error<SessionRequestError>> {
    // add a prefix to parameters to efficiently prevent name collisions
    let p_body_session_request_request = session_request_request;

    let uri_str = format!("{}/auth/v1/sessions/request", 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_session_request_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::SessionRequest200Response`"))),
            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::SessionRequest200Response`")))),
        }
    } else {
        let content = resp.text().await?;
        let entity: Option<SessionRequestError> = serde_json::from_str(&content).ok();
        Err(Error::ResponseError(ResponseContent {
            status,
            content,
            entity,
        }))
    }
}

/// Revoke an authentication token (requires authentication and ownership verification)
pub async fn session_revoke_token_by_id(
    configuration: &configuration::Configuration,
    id: &str,
) -> Result<models::SessionRevokeTokenById200Response, Error<SessionRevokeTokenByIdError>> {
    // add a prefix to parameters to efficiently prevent name collisions
    let p_path_id = id;

    let uri_str = format!(
        "{}/auth/v1/sessions/tokens/{id}",
        configuration.base_path,
        id = crate::doqium_auth_client::apis::urlencode(p_path_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 => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::SessionRevokeTokenById200Response`"))),
            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::SessionRevokeTokenById200Response`")))),
        }
    } else {
        let content = resp.text().await?;
        let entity: Option<SessionRevokeTokenByIdError> = serde_json::from_str(&content).ok();
        Err(Error::ResponseError(ResponseContent {
            status,
            content,
            entity,
        }))
    }
}
