/*
 * 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 [`change_password`]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum ChangePasswordError {
    Status400(models::ErrorModel),
    Status401(models::ErrorModel),
    Status403(models::ErrorModel),
    Status429(models::ErrorModel),
    Status500(models::ErrorModel),
    UnknownValue(serde_json::Value),
}

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

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

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

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

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

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

/// Change a user's password
pub async fn change_password(
    configuration: &configuration::Configuration,
    change_password_request: models::ChangePasswordRequest,
) -> Result<serde_json::Value, Error<ChangePasswordError>> {
    // add a prefix to parameters to efficiently prevent name collisions
    let p_body_change_password_request = change_password_request;

    let uri_str = format!("{}/auth/v1/security/password", configuration.base_path);
    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_change_password_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 `serde_json::Value`"))),
            ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `serde_json::Value`")))),
        }
    } else {
        let content = resp.text().await?;
        let entity: Option<ChangePasswordError> = serde_json::from_str(&content).ok();
        Err(Error::ResponseError(ResponseContent {
            status,
            content,
            entity,
        }))
    }
}

/// Change details of a registered key
pub async fn edit_key(
    configuration: &configuration::Configuration,
    id: &str,
    edit_key_request: models::EditKeyRequest,
) -> Result<models::UserKey, Error<EditKeyError>> {
    // add a prefix to parameters to efficiently prevent name collisions
    let p_path_id = id;
    let p_body_edit_key_request = edit_key_request;

    let uri_str = format!(
        "{}/auth/v1/security/keys/{id}",
        configuration.base_path,
        id = crate::doqium_auth_client::apis::urlencode(p_path_id)
    );
    let mut req_builder = configuration
        .client
        .request(reqwest::Method::PATCH, &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_edit_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 => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::UserKey`"))),
            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::UserKey`")))),
        }
    } else {
        let content = resp.text().await?;
        let entity: Option<EditKeyError> = serde_json::from_str(&content).ok();
        Err(Error::ResponseError(ResponseContent {
            status,
            content,
            entity,
        }))
    }
}

/// Lists registered keys for a user
pub async fn list_user_keys(
    configuration: &configuration::Configuration,
) -> Result<Vec<models::UserKey>, Error<ListUserKeysError>> {
    let uri_str = format!("{}/auth/v1/security/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());
    }

    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::UserKey&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::UserKey&gt;`")))),
        }
    } else {
        let content = resp.text().await?;
        let entity: Option<ListUserKeysError> = serde_json::from_str(&content).ok();
        Err(Error::ResponseError(ResponseContent {
            status,
            content,
            entity,
        }))
    }
}

/// Register a new key for the user to use to log in
pub async fn register_user_key(
    configuration: &configuration::Configuration,
    register_user_key_request: models::RegisterUserKeyRequest,
) -> Result<models::RegisterUserKey200Response, Error<RegisterUserKeyError>> {
    // add a prefix to parameters to efficiently prevent name collisions
    let p_body_register_user_key_request = register_user_key_request;

    let uri_str = format!("{}/auth/v1/security/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());
    }
    req_builder = req_builder.json(&p_body_register_user_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 => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::RegisterUserKey200Response`"))),
            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::RegisterUserKey200Response`")))),
        }
    } else {
        let content = resp.text().await?;
        let entity: Option<RegisterUserKeyError> = serde_json::from_str(&content).ok();
        Err(Error::ResponseError(ResponseContent {
            status,
            content,
            entity,
        }))
    }
}

/// Generates a WebAuthn challenge for the user to pass
pub async fn register_web_authn_challenge(
    configuration: &configuration::Configuration,
) -> Result<models::RegisterWebAuthnChallenge200Response, Error<RegisterWebAuthnChallengeError>> {
    let uri_str = format!(
        "{}/auth/v1/security/webauthn/challenge",
        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 `models::RegisterWebAuthnChallenge200Response`"))),
            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::RegisterWebAuthnChallenge200Response`")))),
        }
    } else {
        let content = resp.text().await?;
        let entity: Option<RegisterWebAuthnChallengeError> = serde_json::from_str(&content).ok();
        Err(Error::ResponseError(ResponseContent {
            status,
            content,
            entity,
        }))
    }
}

/// Request a new reset password email for a user matching provided email
pub async fn request_reset_password(
    configuration: &configuration::Configuration,
    email: &str,
) -> Result<serde_json::Value, Error<RequestResetPasswordError>> {
    // add a prefix to parameters to efficiently prevent name collisions
    let p_query_email = email;

    let uri_str = format!(
        "{}/auth/v1/security/request-reset-password",
        configuration.base_path
    );
    let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str);

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

/// Unregister an existing key of the user
pub async fn unregister_user_key(
    configuration: &configuration::Configuration,
    id: &str,
) -> Result<serde_json::Value, Error<UnregisterUserKeyError>> {
    // add a prefix to parameters to efficiently prevent name collisions
    let p_path_id = id;

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