/*
 * 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 [`add_managed_schema`]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum AddManagedSchemaError {
    Status400(models::ApiErrorResponse),
    Status404(models::ApiErrorResponse),
    Status409(models::ApiErrorResponse),
    UnknownValue(serde_json::Value),
}

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

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

/// struct for typed errors of method [`create_connection`]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum CreateConnectionError {
    Status400(models::ApiErrorResponse),
    Status409(models::ApiErrorResponse),
    UnknownValue(serde_json::Value),
}

/// struct for typed errors of method [`delete_connection`]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum DeleteConnectionError {
    Status404(models::ApiErrorResponse),
    Status409(models::ApiErrorResponse),
    UnknownValue(serde_json::Value),
}

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

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

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

/// struct for typed errors of method [`list_connections`]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum ListConnectionsError {
    UnknownValue(serde_json::Value),
}

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

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

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

/// Declare a new schema (and optionally its tables) on an existing managed catalog after creation. The schema is added to the connection's declaration; declared tables can then be populated via the managed-table load endpoint. Only valid against connections whose source type is `managed`. Identifiers are normalised to lowercase.
pub async fn add_managed_schema(
    configuration: &configuration::Configuration,
    connection_id: &str,
    add_managed_schema_request: models::AddManagedSchemaRequest,
) -> Result<models::ManagedSchemaResponse, Error<AddManagedSchemaError>> {
    // add a prefix to parameters to efficiently prevent name collisions
    let p_path_connection_id = connection_id;
    let p_body_add_managed_schema_request = add_managed_schema_request;

    let uri_str = format!(
        "{}/v1/connections/{connection_id}/schemas",
        configuration.base_path,
        connection_id = crate::apis::urlencode(p_path_connection_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(apikey) = configuration.api_keys.get("X-Workspace-Id") {
        let key = apikey.key.clone();
        let value = match apikey.prefix {
            Some(ref prefix) => format!("{} {}", prefix, key),
            None => key,
        };
        req_builder = req_builder.header("X-Workspace-Id", value);
    };
    if let Some(token) = configuration.resolve_bearer_token().await {
        req_builder = req_builder.bearer_auth(token);
    };
    req_builder = req_builder.json(&p_body_add_managed_schema_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::ManagedSchemaResponse`"))),
            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::ManagedSchemaResponse`")))),
        }
    } else {
        let content = resp.text().await?;
        crate::http_log::log_response_body(&content);
        let entity: Option<AddManagedSchemaError> = serde_json::from_str(&content).ok();
        Err(Error::ResponseError(ResponseContent {
            status,
            content,
            entity,
        }))
    }
}

/// Declare a new table on an existing schema of a managed catalog after creation. The table is added empty (declared-but-unloaded) and can be populated via the managed-table load endpoint. Only valid against connections whose source type is `managed`. Identifiers are normalised to lowercase.
pub async fn add_managed_table(
    configuration: &configuration::Configuration,
    connection_id: &str,
    schema: &str,
    add_managed_table_request: models::AddManagedTableRequest,
) -> Result<models::ManagedTableResponse, Error<AddManagedTableError>> {
    // add a prefix to parameters to efficiently prevent name collisions
    let p_path_connection_id = connection_id;
    let p_path_schema = schema;
    let p_body_add_managed_table_request = add_managed_table_request;

    let uri_str = format!(
        "{}/v1/connections/{connection_id}/schemas/{schema}/tables",
        configuration.base_path,
        connection_id = crate::apis::urlencode(p_path_connection_id),
        schema = crate::apis::urlencode(p_path_schema)
    );
    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(apikey) = configuration.api_keys.get("X-Workspace-Id") {
        let key = apikey.key.clone();
        let value = match apikey.prefix {
            Some(ref prefix) => format!("{} {}", prefix, key),
            None => key,
        };
        req_builder = req_builder.header("X-Workspace-Id", value);
    };
    if let Some(token) = configuration.resolve_bearer_token().await {
        req_builder = req_builder.bearer_auth(token);
    };
    req_builder = req_builder.json(&p_body_add_managed_table_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::ManagedTableResponse`"))),
            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::ManagedTableResponse`")))),
        }
    } else {
        let content = resp.text().await?;
        crate::http_log::log_response_body(&content);
        let entity: Option<AddManagedTableError> = serde_json::from_str(&content).ok();
        Err(Error::ResponseError(ResponseContent {
            status,
            content,
            entity,
        }))
    }
}

/// Test connectivity to the remote database. Returns health status and latency.
pub async fn check_connection_health(
    configuration: &configuration::Configuration,
    connection_id: &str,
) -> Result<models::ConnectionHealthResponse, Error<CheckConnectionHealthError>> {
    // add a prefix to parameters to efficiently prevent name collisions
    let p_path_connection_id = connection_id;

    let uri_str = format!(
        "{}/v1/connections/{connection_id}/health",
        configuration.base_path,
        connection_id = crate::apis::urlencode(p_path_connection_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(apikey) = configuration.api_keys.get("X-Workspace-Id") {
        let key = apikey.key.clone();
        let value = match apikey.prefix {
            Some(ref prefix) => format!("{} {}", prefix, key),
            None => key,
        };
        req_builder = req_builder.header("X-Workspace-Id", value);
    };
    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::ConnectionHealthResponse`"))),
            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::ConnectionHealthResponse`")))),
        }
    } else {
        let content = resp.text().await?;
        crate::http_log::log_response_body(&content);
        let entity: Option<CheckConnectionHealthError> = serde_json::from_str(&content).ok();
        Err(Error::ResponseError(ResponseContent {
            status,
            content,
            entity,
        }))
    }
}

/// Register a new database connection. Provide the source type and connection config (host, port, database, etc.). Credentials can be supplied inline (password/token fields are auto-converted to secrets) or by referencing an existing secret by name or ID. Schema discovery runs automatically after registration.
pub async fn create_connection(
    configuration: &configuration::Configuration,
    create_connection_request: models::CreateConnectionRequest,
) -> Result<models::CreateConnectionResponse, Error<CreateConnectionError>> {
    // add a prefix to parameters to efficiently prevent name collisions
    let p_body_create_connection_request = create_connection_request;

    let uri_str = format!("{}/v1/connections", 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(apikey) = configuration.api_keys.get("X-Workspace-Id") {
        let key = apikey.key.clone();
        let value = match apikey.prefix {
            Some(ref prefix) => format!("{} {}", prefix, key),
            None => key,
        };
        req_builder = req_builder.header("X-Workspace-Id", value);
    };
    if let Some(token) = configuration.resolve_bearer_token().await {
        req_builder = req_builder.bearer_auth(token);
    };
    req_builder = req_builder.json(&p_body_create_connection_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::CreateConnectionResponse`"))),
            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::CreateConnectionResponse`")))),
        }
    } else {
        let content = resp.text().await?;
        crate::http_log::log_response_body(&content);
        let entity: Option<CreateConnectionError> = serde_json::from_str(&content).ok();
        Err(Error::ResponseError(ResponseContent {
            status,
            content,
            entity,
        }))
    }
}

/// Delete a connection and its cached data.
pub async fn delete_connection(
    configuration: &configuration::Configuration,
    connection_id: &str,
) -> Result<(), Error<DeleteConnectionError>> {
    // add a prefix to parameters to efficiently prevent name collisions
    let p_path_connection_id = connection_id;

    let uri_str = format!(
        "{}/v1/connections/{connection_id}",
        configuration.base_path,
        connection_id = crate::apis::urlencode(p_path_connection_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(apikey) = configuration.api_keys.get("X-Workspace-Id") {
        let key = apikey.key.clone();
        let value = match apikey.prefix {
            Some(ref prefix) => format!("{} {}", prefix, key),
            None => key,
        };
        req_builder = req_builder.header("X-Workspace-Id", value);
    };
    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<DeleteConnectionError> = serde_json::from_str(&content).ok();
        Err(Error::ResponseError(ResponseContent {
            status,
            content,
            entity,
        }))
    }
}

/// Delete a single managed-catalog table. The catalog row is removed and the backing parquet file (if any) is scheduled for deletion. Only valid against connections whose source type is `managed`.
pub async fn delete_managed_table(
    configuration: &configuration::Configuration,
    connection_id: &str,
    schema: &str,
    table: &str,
) -> Result<(), Error<DeleteManagedTableError>> {
    // add a prefix to parameters to efficiently prevent name collisions
    let p_path_connection_id = connection_id;
    let p_path_schema = schema;
    let p_path_table = table;

    let uri_str = format!(
        "{}/v1/connections/{connection_id}/schemas/{schema}/tables/{table}",
        configuration.base_path,
        connection_id = crate::apis::urlencode(p_path_connection_id),
        schema = crate::apis::urlencode(p_path_schema),
        table = crate::apis::urlencode(p_path_table)
    );
    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(apikey) = configuration.api_keys.get("X-Workspace-Id") {
        let key = apikey.key.clone();
        let value = match apikey.prefix {
            Some(ref prefix) => format!("{} {}", prefix, key),
            None => key,
        };
        req_builder = req_builder.header("X-Workspace-Id", value);
    };
    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<DeleteManagedTableError> = serde_json::from_str(&content).ok();
        Err(Error::ResponseError(ResponseContent {
            status,
            content,
            entity,
        }))
    }
}

/// Get details for a specific connection, including table and sync counts.
pub async fn get_connection(
    configuration: &configuration::Configuration,
    connection_id: &str,
) -> Result<models::GetConnectionResponse, Error<GetConnectionError>> {
    // add a prefix to parameters to efficiently prevent name collisions
    let p_path_connection_id = connection_id;

    let uri_str = format!(
        "{}/v1/connections/{connection_id}",
        configuration.base_path,
        connection_id = crate::apis::urlencode(p_path_connection_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(apikey) = configuration.api_keys.get("X-Workspace-Id") {
        let key = apikey.key.clone();
        let value = match apikey.prefix {
            Some(ref prefix) => format!("{} {}", prefix, key),
            None => key,
        };
        req_builder = req_builder.header("X-Workspace-Id", value);
    };
    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::GetConnectionResponse`"))),
            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::GetConnectionResponse`")))),
        }
    } else {
        let content = resp.text().await?;
        crate::http_log::log_response_body(&content);
        let entity: Option<GetConnectionError> = serde_json::from_str(&content).ok();
        Err(Error::ResponseError(ResponseContent {
            status,
            content,
            entity,
        }))
    }
}

/// Get column-level statistics for a synced table. Returns per-column profiles including cardinality, null counts, and type-specific details (distinct values for categorical columns, min/max for temporal/numeric, length stats for text). Profiles are computed at sync time.
pub async fn get_table_profile(
    configuration: &configuration::Configuration,
    connection_id: &str,
    schema: &str,
    table: &str,
) -> Result<models::TableProfileResponse, Error<GetTableProfileError>> {
    // add a prefix to parameters to efficiently prevent name collisions
    let p_path_connection_id = connection_id;
    let p_path_schema = schema;
    let p_path_table = table;

    let uri_str = format!(
        "{}/v1/connections/{connection_id}/tables/{schema}/{table}/profile",
        configuration.base_path,
        connection_id = crate::apis::urlencode(p_path_connection_id),
        schema = crate::apis::urlencode(p_path_schema),
        table = crate::apis::urlencode(p_path_table)
    );
    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(apikey) = configuration.api_keys.get("X-Workspace-Id") {
        let key = apikey.key.clone();
        let value = match apikey.prefix {
            Some(ref prefix) => format!("{} {}", prefix, key),
            None => key,
        };
        req_builder = req_builder.header("X-Workspace-Id", value);
    };
    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::TableProfileResponse`"))),
            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::TableProfileResponse`")))),
        }
    } else {
        let content = resp.text().await?;
        crate::http_log::log_response_body(&content);
        let entity: Option<GetTableProfileError> = serde_json::from_str(&content).ok();
        Err(Error::ResponseError(ResponseContent {
            status,
            content,
            entity,
        }))
    }
}

/// List all registered database connections.
pub async fn list_connections(
    configuration: &configuration::Configuration,
) -> Result<models::ListConnectionsResponse, Error<ListConnectionsError>> {
    let uri_str = format!("{}/v1/connections", 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());
    }
    if let Some(apikey) = configuration.api_keys.get("X-Workspace-Id") {
        let key = apikey.key.clone();
        let value = match apikey.prefix {
            Some(ref prefix) => format!("{} {}", prefix, key),
            None => key,
        };
        req_builder = req_builder.header("X-Workspace-Id", value);
    };
    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::ListConnectionsResponse`"))),
            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::ListConnectionsResponse`")))),
        }
    } else {
        let content = resp.text().await?;
        crate::http_log::log_response_body(&content);
        let entity: Option<ListConnectionsError> = serde_json::from_str(&content).ok();
        Err(Error::ResponseError(ResponseContent {
            status,
            content,
            entity,
        }))
    }
}

/// Publish a previously-uploaded parquet file as the new generation of a managed table. The upload must reference a parquet file (verified by magic bytes). Only `mode = \"replace\"` is supported. Concurrent loads against the same upload return 409.
pub async fn load_managed_table(
    configuration: &configuration::Configuration,
    connection_id: &str,
    schema: &str,
    table: &str,
    load_managed_table_request: models::LoadManagedTableRequest,
) -> Result<models::LoadManagedTableResponse, Error<LoadManagedTableError>> {
    // add a prefix to parameters to efficiently prevent name collisions
    let p_path_connection_id = connection_id;
    let p_path_schema = schema;
    let p_path_table = table;
    let p_body_load_managed_table_request = load_managed_table_request;

    let uri_str = format!(
        "{}/v1/connections/{connection_id}/schemas/{schema}/tables/{table}/loads",
        configuration.base_path,
        connection_id = crate::apis::urlencode(p_path_connection_id),
        schema = crate::apis::urlencode(p_path_schema),
        table = crate::apis::urlencode(p_path_table)
    );
    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(apikey) = configuration.api_keys.get("X-Workspace-Id") {
        let key = apikey.key.clone();
        let value = match apikey.prefix {
            Some(ref prefix) => format!("{} {}", prefix, key),
            None => key,
        };
        req_builder = req_builder.header("X-Workspace-Id", value);
    };
    if let Some(token) = configuration.resolve_bearer_token().await {
        req_builder = req_builder.bearer_auth(token);
    };
    req_builder = req_builder.json(&p_body_load_managed_table_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::LoadManagedTableResponse`"))),
            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::LoadManagedTableResponse`")))),
        }
    } else {
        let content = resp.text().await?;
        crate::http_log::log_response_body(&content);
        let entity: Option<LoadManagedTableError> = serde_json::from_str(&content).ok();
        Err(Error::ResponseError(ResponseContent {
            status,
            content,
            entity,
        }))
    }
}

/// Purge all cached data for a connection. The next query against these tables will trigger a fresh sync from the remote source.
pub async fn purge_connection_cache(
    configuration: &configuration::Configuration,
    connection_id: &str,
) -> Result<(), Error<PurgeConnectionCacheError>> {
    // add a prefix to parameters to efficiently prevent name collisions
    let p_path_connection_id = connection_id;

    let uri_str = format!(
        "{}/v1/connections/{connection_id}/cache",
        configuration.base_path,
        connection_id = crate::apis::urlencode(p_path_connection_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(apikey) = configuration.api_keys.get("X-Workspace-Id") {
        let key = apikey.key.clone();
        let value = match apikey.prefix {
            Some(ref prefix) => format!("{} {}", prefix, key),
            None => key,
        };
        req_builder = req_builder.header("X-Workspace-Id", value);
    };
    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<PurgeConnectionCacheError> = serde_json::from_str(&content).ok();
        Err(Error::ResponseError(ResponseContent {
            status,
            content,
            entity,
        }))
    }
}

/// Purge the cached data for a single table. The next query will trigger a fresh sync.
pub async fn purge_table_cache(
    configuration: &configuration::Configuration,
    connection_id: &str,
    schema: &str,
    table: &str,
) -> Result<(), Error<PurgeTableCacheError>> {
    // add a prefix to parameters to efficiently prevent name collisions
    let p_path_connection_id = connection_id;
    let p_path_schema = schema;
    let p_path_table = table;

    let uri_str = format!(
        "{}/v1/connections/{connection_id}/tables/{schema}/{table}/cache",
        configuration.base_path,
        connection_id = crate::apis::urlencode(p_path_connection_id),
        schema = crate::apis::urlencode(p_path_schema),
        table = crate::apis::urlencode(p_path_table)
    );
    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(apikey) = configuration.api_keys.get("X-Workspace-Id") {
        let key = apikey.key.clone();
        let value = match apikey.prefix {
            Some(ref prefix) => format!("{} {}", prefix, key),
            None => key,
        };
        req_builder = req_builder.header("X-Workspace-Id", value);
    };
    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<PurgeTableCacheError> = serde_json::from_str(&content).ok();
        Err(Error::ResponseError(ResponseContent {
            status,
            content,
            entity,
        }))
    }
}
