/*
 * Zernio API
 *
 * API reference for Zernio. Authenticate with a Bearer API key. Base URL: https://zernio.com/api
 *
 * The version of the OpenAPI document: 1.0.4
 * Contact: support@zernio.com
 * 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 [`disable_whats_app_calling`]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum DisableWhatsAppCallingError {
    Status401(models::InlineObject),
    Status404(),
    UnknownValue(serde_json::Value),
}

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

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

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

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

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

/// struct for typed errors of method [`initiate_whats_app_call`]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum InitiateWhatsAppCallError {
    Status401(models::InlineObject),
    Status409(),
    Status422(),
    Status502(),
    UnknownValue(serde_json::Value),
}

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

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

/// Disable calling. Sends calling.status=DISABLED to Meta (best-effort) and flips the local `callingEnabled` flag off. forwardTo and SIP creds are preserved so a re-enable does not lose the destination.
pub async fn disable_whats_app_calling(
    configuration: &configuration::Configuration,
    id: &str,
    account_id: &str,
) -> Result<(), Error<DisableWhatsAppCallingError>> {
    // add a prefix to parameters to efficiently prevent name collisions
    let p_path_id = id;
    let p_query_account_id = account_id;

    let uri_str = format!(
        "{}/v1/whatsapp/phone-numbers/{id}/calling",
        configuration.base_path,
        id = crate::apis::urlencode(p_path_id)
    );
    let mut req_builder = configuration
        .client
        .request(reqwest::Method::DELETE, &uri_str);

    req_builder = req_builder.query(&[("accountId", &p_query_account_id.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(ref token) = configuration.bearer_access_token {
        req_builder = req_builder.bearer_auth(token.to_owned());
    };

    let req = req_builder.build()?;
    let resp = configuration.client.execute(req).await?;

    let status = resp.status();

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

/// Enable WhatsApp Business Calling on a connected number. Configures Meta calling.status=ENABLED with our Telnyx SIP endpoint, fetches and stores the Meta-issued SIP password (encrypted), and snapshots the customer's forward-to destination.
pub async fn enable_whats_app_calling(
    configuration: &configuration::Configuration,
    id: &str,
    enable_whats_app_calling_request: models::EnableWhatsAppCallingRequest,
) -> Result<models::EnableWhatsAppCalling200Response, Error<EnableWhatsAppCallingError>> {
    // add a prefix to parameters to efficiently prevent name collisions
    let p_path_id = id;
    let p_body_enable_whats_app_calling_request = enable_whats_app_calling_request;

    let uri_str = format!(
        "{}/v1/whatsapp/phone-numbers/{id}/calling",
        configuration.base_path,
        id = crate::apis::urlencode(p_path_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(ref token) = configuration.bearer_access_token {
        req_builder = req_builder.bearer_auth(token.to_owned());
    };
    req_builder = req_builder.json(&p_body_enable_whats_app_calling_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::EnableWhatsAppCalling200Response`"))),
            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::EnableWhatsAppCalling200Response`")))),
        }
    } else {
        let content = resp.text().await?;
        let entity: Option<EnableWhatsAppCallingError> = serde_json::from_str(&content).ok();
        Err(Error::ResponseError(ResponseContent {
            status,
            content,
            entity,
        }))
    }
}

pub async fn get_whats_app_call(
    configuration: &configuration::Configuration,
    call_id: &str,
    account_id: &str,
) -> Result<models::GetWhatsAppCall200Response, Error<GetWhatsAppCallError>> {
    // add a prefix to parameters to efficiently prevent name collisions
    let p_path_call_id = call_id;
    let p_query_account_id = account_id;

    let uri_str = format!(
        "{}/v1/whatsapp/calls/{callId}",
        configuration.base_path,
        callId = crate::apis::urlencode(p_path_call_id)
    );
    let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str);

    req_builder = req_builder.query(&[("accountId", &p_query_account_id.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(ref token) = configuration.bearer_access_token {
        req_builder = req_builder.bearer_auth(token.to_owned());
    };

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

/// Returns a zero-markup estimated cost for an outbound call to the given destination, broken down by Meta + Telnyx + recording line items. Costs are pass-through, no margin applied.
pub async fn get_whats_app_call_estimate(
    configuration: &configuration::Configuration,
    account_id: &str,
    to: &str,
    minutes: Option<i32>,
    recording: Option<bool>,
) -> Result<models::GetWhatsAppCallEstimate200Response, Error<GetWhatsAppCallEstimateError>> {
    // add a prefix to parameters to efficiently prevent name collisions
    let p_query_account_id = account_id;
    let p_query_to = to;
    let p_query_minutes = minutes;
    let p_query_recording = recording;

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

    req_builder = req_builder.query(&[("accountId", &p_query_account_id.to_string())]);
    req_builder = req_builder.query(&[("to", &p_query_to.to_string())]);
    if let Some(ref param_value) = p_query_minutes {
        req_builder = req_builder.query(&[("minutes", &param_value.to_string())]);
    }
    if let Some(ref param_value) = p_query_recording {
        req_builder = req_builder.query(&[("recording", &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(ref token) = configuration.bearer_access_token {
        req_builder = req_builder.bearer_auth(token.to_owned());
    };

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

/// Returns the permission state and the list of available actions for a given consumer wa_id (e.g. `start_call`, `send_call_permission_request`). Use this before placing a call to decide whether to prompt for consent first.
pub async fn get_whats_app_call_permissions(
    configuration: &configuration::Configuration,
    account_id: &str,
    to: &str,
) -> Result<models::GetWhatsAppCallPermissions200Response, Error<GetWhatsAppCallPermissionsError>> {
    // add a prefix to parameters to efficiently prevent name collisions
    let p_query_account_id = account_id;
    let p_query_to = to;

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

    req_builder = req_builder.query(&[("accountId", &p_query_account_id.to_string())]);
    req_builder = req_builder.query(&[("to", &p_query_to.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(ref token) = configuration.bearer_access_token {
        req_builder = req_builder.bearer_auth(token.to_owned());
    };

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

/// Returns the local calling configuration snapshot for the connected WhatsApp account: whether calling is enabled, the forward-to destination URI, recording opt-in state, the WhatsAppPhoneNumber doc id (use as `{id}` on the calling-config write endpoints) and whether SIP digest credentials are stored (the encrypted password itself is never returned).
pub async fn get_whats_app_calling_config(
    configuration: &configuration::Configuration,
    account_id: &str,
) -> Result<models::GetWhatsAppCallingConfig200Response, Error<GetWhatsAppCallingConfigError>> {
    // add a prefix to parameters to efficiently prevent name collisions
    let p_query_account_id = account_id;

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

    req_builder = req_builder.query(&[("accountId", &p_query_account_id.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(ref token) = configuration.bearer_access_token {
        req_builder = req_builder.bearer_auth(token.to_owned());
    };

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

/// Initiates an outbound Business-Initiated Call. The Telnyx-side SIP leg is originated server-side (Option B: SIP-first). Telnyx INVITEs Meta directly over TLS:5061 with the SIP digest credentials we captured at calling-enablement time). No client-side SDP is required; pass only `accountId` and `to`.
pub async fn initiate_whats_app_call(
    configuration: &configuration::Configuration,
    initiate_whats_app_call_request: models::InitiateWhatsAppCallRequest,
) -> Result<models::InitiateWhatsAppCall200Response, Error<InitiateWhatsAppCallError>> {
    // add a prefix to parameters to efficiently prevent name collisions
    let p_body_initiate_whats_app_call_request = initiate_whats_app_call_request;

    let uri_str = format!("{}/v1/whatsapp/calls", 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(ref token) = configuration.bearer_access_token {
        req_builder = req_builder.bearer_auth(token.to_owned());
    };
    req_builder = req_builder.json(&p_body_initiate_whats_app_call_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::InitiateWhatsAppCall200Response`"))),
            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::InitiateWhatsAppCall200Response`")))),
        }
    } else {
        let content = resp.text().await?;
        let entity: Option<InitiateWhatsAppCallError> = serde_json::from_str(&content).ok();
        Err(Error::ResponseError(ResponseContent {
            status,
            content,
            entity,
        }))
    }
}

/// Compact history listing for a single connected account. Results are scoped to the resolved SocialAccount; profile-scoped team members cannot read calls on sibling accounts.
pub async fn list_whats_app_calls(
    configuration: &configuration::Configuration,
    account_id: &str,
    status: Option<&str>,
    direction: Option<&str>,
    since: Option<String>,
    until: Option<String>,
    limit: Option<i32>,
) -> Result<models::ListWhatsAppCalls200Response, Error<ListWhatsAppCallsError>> {
    // add a prefix to parameters to efficiently prevent name collisions
    let p_query_account_id = account_id;
    let p_query_status = status;
    let p_query_direction = direction;
    let p_query_since = since;
    let p_query_until = until;
    let p_query_limit = limit;

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

    req_builder = req_builder.query(&[("accountId", &p_query_account_id.to_string())]);
    if let Some(ref param_value) = p_query_status {
        req_builder = req_builder.query(&[("status", &param_value.to_string())]);
    }
    if let Some(ref param_value) = p_query_direction {
        req_builder = req_builder.query(&[("direction", &param_value.to_string())]);
    }
    if let Some(ref param_value) = p_query_since {
        req_builder = req_builder.query(&[("since", &param_value.to_string())]);
    }
    if let Some(ref param_value) = p_query_until {
        req_builder = req_builder.query(&[("until", &param_value.to_string())]);
    }
    if let Some(ref param_value) = p_query_limit {
        req_builder = req_builder.query(&[("limit", &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(ref token) = configuration.bearer_access_token {
        req_builder = req_builder.bearer_auth(token.to_owned());
    };

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

/// Update fields on an already-enabled number. Only fields present in the body are written; `undefined` leaves the stored value alone, explicit `null` clears a nullable field. No Meta side effect, this only changes local routing state consumed by the Telnyx webhook handler.
pub async fn update_whats_app_calling(
    configuration: &configuration::Configuration,
    id: &str,
    update_whats_app_calling_request: models::UpdateWhatsAppCallingRequest,
) -> Result<(), Error<UpdateWhatsAppCallingError>> {
    // add a prefix to parameters to efficiently prevent name collisions
    let p_path_id = id;
    let p_body_update_whats_app_calling_request = update_whats_app_calling_request;

    let uri_str = format!(
        "{}/v1/whatsapp/phone-numbers/{id}/calling",
        configuration.base_path,
        id = crate::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());
    }
    if let Some(ref token) = configuration.bearer_access_token {
        req_builder = req_builder.bearer_auth(token.to_owned());
    };
    req_builder = req_builder.json(&p_body_update_whats_app_calling_request);

    let req = req_builder.build()?;
    let resp = configuration.client.execute(req).await?;

    let status = resp.status();

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