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

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

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

/// Prepare subscriptions according to the purchase data in the receipt
pub async fn process_store_receipt(
    configuration: &configuration::Configuration,
    source: &str,
    process_store_receipt_request: models::ProcessStoreReceiptRequest,
) -> Result<models::ProcessStoreReceipt200Response, Error<ProcessStoreReceiptError>> {
    // add a prefix to parameters to efficiently prevent name collisions
    let p_path_source = source;
    let p_body_process_store_receipt_request = process_store_receipt_request;

    let uri_str = format!(
        "{}/api/v1/subscriptions/store/{source}/receipt",
        configuration.base_path,
        source = crate::doqium_auth_client::apis::urlencode(p_path_source)
    );
    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_process_store_receipt_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::ProcessStoreReceipt200Response`"))),
            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::ProcessStoreReceipt200Response`")))),
        }
    } else {
        let content = resp.text().await?;
        let entity: Option<ProcessStoreReceiptError> = serde_json::from_str(&content).ok();
        Err(Error::ResponseError(ResponseContent {
            status,
            content,
            entity,
        }))
    }
}

/// Subscribe current user to plan
pub async fn subscribe_to_plan(
    configuration: &configuration::Configuration,
    source: &str,
    plan_id: &str,
    body: serde_json::Value,
) -> Result<models::SubscribeToPlan200Response, Error<SubscribeToPlanError>> {
    // add a prefix to parameters to efficiently prevent name collisions
    let p_path_source = source;
    let p_path_plan_id = plan_id;
    let p_body_body = body;

    let uri_str = format!(
        "{}/auth/v1/subscriptions/{source}/{planId}",
        configuration.base_path,
        source = crate::doqium_auth_client::apis::urlencode(p_path_source),
        planId = crate::doqium_auth_client::apis::urlencode(p_path_plan_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());
    }
    req_builder = req_builder.json(&p_body_body);

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

/// Remove current user from plan
pub async fn unsubscribe_from_plan(
    configuration: &configuration::Configuration,
    source: &str,
    plan_id: &str,
) -> Result<serde_json::Value, Error<UnsubscribeFromPlanError>> {
    // add a prefix to parameters to efficiently prevent name collisions
    let p_path_source = source;
    let p_path_plan_id = plan_id;

    let uri_str = format!(
        "{}/auth/v1/subscriptions/{source}/{planId}",
        configuration.base_path,
        source = crate::doqium_auth_client::apis::urlencode(p_path_source),
        planId = crate::doqium_auth_client::apis::urlencode(p_path_plan_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<UnsubscribeFromPlanError> = serde_json::from_str(&content).ok();
        Err(Error::ResponseError(ResponseContent {
            status,
            content,
            entity,
        }))
    }
}
