/*
 * Hotdata API
 *
 * Powerful data platform API for datasets, queries, and analytics.
 *
 * The version of the OpenAPI document: 1.0.0
 * Contact: developers@hotdata.dev
 * Generated by: https://openapi-generator.tech
 */

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

/// struct for typed errors of method [`create_workspace`]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum CreateWorkspaceError {
    Status400(models::Error),
    Status401(models::Error),
    Status403(models::Error),
    Status404(models::Error),
    Status422(models::Error),
    UnknownValue(serde_json::Value),
}

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

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

/// Creates a new workspace in the specified organization.
pub async fn create_workspace(
    configuration: &configuration::Configuration,
    create_workspace_request: models::CreateWorkspaceRequest,
) -> Result<models::CreateWorkspaceResponse, Error<CreateWorkspaceError>> {
    // add a prefix to parameters to efficiently prevent name collisions
    let p_body_create_workspace_request = create_workspace_request;

    let uri_str = format!("{}/v1/workspaces", 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());
    }
    if let Some(token) = configuration.resolve_bearer_token().await {
        req_builder = req_builder.bearer_auth(token);
    };
    req_builder = req_builder.json(&p_body_create_workspace_request);

    let req = req_builder.build()?;
    crate::http_log::log_request(&req);
    let resp = configuration.client.execute(req).await?;

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

/// Hard-deletes the workspace. Namespace, storage, and catalog deprovisioning runs asynchronously after the row is removed.
pub async fn delete_workspace(
    configuration: &configuration::Configuration,
    public_id: &str,
) -> Result<(), Error<DeleteWorkspaceError>> {
    // add a prefix to parameters to efficiently prevent name collisions
    let p_path_public_id = public_id;

    let uri_str = format!(
        "{}/v1/workspaces/{public_id}",
        configuration.base_path,
        public_id = crate::apis::urlencode(p_path_public_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());
    }
    if let Some(token) = configuration.resolve_bearer_token().await {
        req_builder = req_builder.bearer_auth(token);
    };

    let req = req_builder.build()?;
    crate::http_log::log_request(&req);
    let resp = configuration.client.execute(req).await?;

    let status = resp.status();
    crate::http_log::log_response_status(status);

    if !status.is_client_error() && !status.is_server_error() {
        Ok(())
    } else {
        let content = resp.text().await?;
        crate::http_log::log_response_body(&content);
        let entity: Option<DeleteWorkspaceError> = serde_json::from_str(&content).ok();
        Err(Error::ResponseError(ResponseContent {
            status,
            content,
            entity,
        }))
    }
}

/// Lists all workspaces in the user's organization.
pub async fn list_workspaces(
    configuration: &configuration::Configuration,
    organization_public_id: Option<&str>,
) -> Result<models::ListWorkspacesResponse, Error<ListWorkspacesError>> {
    // add a prefix to parameters to efficiently prevent name collisions
    let p_query_organization_public_id = organization_public_id;

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

    if let Some(ref param_value) = p_query_organization_public_id {
        req_builder = req_builder.query(&[("organization_public_id", &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(token) = configuration.resolve_bearer_token().await {
        req_builder = req_builder.bearer_auth(token);
    };

    let req = req_builder.build()?;
    crate::http_log::log_request(&req);
    let resp = configuration.client.execute(req).await?;

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