// Copyright 2022 Rigetti Computing
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/*
 * Rigetti QCS API
 *
 * # Introduction  This is the documentation for the Rigetti QCS HTTP API.  You can find out more about Rigetti at [https://rigetti.com](https://rigetti.com), and also interact with QCS via the web at [https://qcs.rigetti.com](https://qcs.rigetti.com).  This API is documented in **OpenAPI format** and so is compatible with the dozens of language-specific client generators available [here](https://github.com/OpenAPITools/openapi-generator) and elsewhere on the web.  # Principles  This API follows REST design principles where appropriate, and otherwise an HTTP RPC paradigm. We adhere to the Google [API Improvement Proposals](https://google.aip.dev/general) where reasonable to provide a consistent, intuitive developer experience. HTTP response codes match their specifications, and error messages fit a common format.  # Authentication  All access to the QCS API requires OAuth2 authentication provided by Okta. You can request access [here](https://www.rigetti.com/get-quantum). Once you have a user account, you can download your access token from QCS [here](https://qcs.rigetti.com/auth/token).   That access token is valid for 24 hours after issuance. The value of `access_token` within the JSON file is the token used for authentication (don't use the entire JSON file).  Authenticate requests using the `Authorization` header and a `Bearer` prefix:  ``` curl --header \"Authorization: Bearer eyJraW...Iow\" ```  # Quantum Processor Access  Access to the quantum processors themselves is not yet provided directly by this HTTP API, but is instead performed over ZeroMQ/[rpcq](https://github.com/rigetti/rpcq). Until that changes, we suggest using [pyquil](https://github.com/rigetti/pyquil) to build and execute quantum programs via the Legacy API.  # Legacy API  Our legacy HTTP API remains accessible at https://forest-server.qcs.rigetti.com, and it shares a source of truth with this API's services. You can use either service with the same user account and means of authentication. We strongly recommend using the API documented here, as the legacy API is on the path to deprecation.
 *
 * The version of the OpenAPI document: 2020-07-31
 * Contact: support@rigetti.com
 * Generated by: https://openapi-generator.tech
 */

use super::{configuration, ContentType, Error};
use crate::{apis::ResponseContent, models};
use ::qcs_api_client_common::backoff::{
    duration_from_io_error, duration_from_reqwest_error, duration_from_response, ExponentialBackoff,
};
#[cfg(feature = "tracing")]
use qcs_api_client_common::configuration::tokens::TokenRefresher;
use reqwest::StatusCode;
use serde::{Deserialize, Serialize};

#[cfg(feature = "clap")]
#[allow(unused, reason = "not used in all templates, but required in some")]
use ::{miette::IntoDiagnostic as _, qcs_api_client_common::clap_utils::JsonMaybeStdin};

/// Serialize command-line arguments for [`activate_user`]
#[cfg(feature = "clap")]
#[derive(Debug, clap::Args)]
pub struct ActivateUserClapParams {
    pub activate_user_request: Option<JsonMaybeStdin<crate::models::ActivateUserRequest>>,
}

#[cfg(feature = "clap")]
impl ActivateUserClapParams {
    pub async fn execute(
        self,
        configuration: &configuration::Configuration,
    ) -> Result<models::User, miette::Error> {
        let request = self
            .activate_user_request
            .map(|body| body.into_inner().into_inner());

        activate_user(configuration, request)
            .await
            .into_diagnostic()
    }
}

/// Serialize command-line arguments for [`add_group_user`]
#[cfg(feature = "clap")]
#[derive(Debug, clap::Args)]
pub struct AddGroupUserClapParams {
    pub add_group_user_request: JsonMaybeStdin<crate::models::AddGroupUserRequest>,
}

#[cfg(feature = "clap")]
impl AddGroupUserClapParams {
    pub async fn execute(
        self,
        configuration: &configuration::Configuration,
    ) -> Result<(), miette::Error> {
        let request = self.add_group_user_request.into_inner().into_inner();

        add_group_user(configuration, request)
            .await
            .into_diagnostic()
    }
}

/// Serialize command-line arguments for [`dismiss_viewer_announcement`]
#[cfg(feature = "clap")]
#[derive(Debug, clap::Args)]
pub struct DismissViewerAnnouncementClapParams {
    /// The ID of an existing announcement.
    #[arg(long)]
    pub announcement_id: i64,
}

#[cfg(feature = "clap")]
impl DismissViewerAnnouncementClapParams {
    pub async fn execute(
        self,
        configuration: &configuration::Configuration,
    ) -> Result<(), miette::Error> {
        dismiss_viewer_announcement(configuration, self.announcement_id)
            .await
            .into_diagnostic()
    }
}

/// Serialize command-line arguments for [`get_group_balance`]
#[cfg(feature = "clap")]
#[derive(Debug, clap::Args)]
pub struct GetGroupBalanceClapParams {
    /// URL encoded name of group for which to retrieve account balance.
    #[arg(long)]
    pub group_name: String,
}

#[cfg(feature = "clap")]
impl GetGroupBalanceClapParams {
    pub async fn execute(
        self,
        configuration: &configuration::Configuration,
    ) -> Result<models::AccountBalance, miette::Error> {
        get_group_balance(configuration, self.group_name.as_str())
            .await
            .into_diagnostic()
    }
}

/// Serialize command-line arguments for [`get_group_billing_customer`]
#[cfg(feature = "clap")]
#[derive(Debug, clap::Args)]
pub struct GetGroupBillingCustomerClapParams {
    /// URL-encoded name of group.
    #[arg(long)]
    pub group_name: String,
}

#[cfg(feature = "clap")]
impl GetGroupBillingCustomerClapParams {
    pub async fn execute(
        self,
        configuration: &configuration::Configuration,
    ) -> Result<models::BillingCustomer, miette::Error> {
        get_group_billing_customer(configuration, self.group_name.as_str())
            .await
            .into_diagnostic()
    }
}

/// Serialize command-line arguments for [`get_group_upcoming_billing_invoice`]
#[cfg(feature = "clap")]
#[derive(Debug, clap::Args)]
pub struct GetGroupUpcomingBillingInvoiceClapParams {
    /// URL-encoded name of group.
    #[arg(long)]
    pub group_name: String,
}

#[cfg(feature = "clap")]
impl GetGroupUpcomingBillingInvoiceClapParams {
    pub async fn execute(
        self,
        configuration: &configuration::Configuration,
    ) -> Result<models::BillingUpcomingInvoice, miette::Error> {
        get_group_upcoming_billing_invoice(configuration, self.group_name.as_str())
            .await
            .into_diagnostic()
    }
}

/// Serialize command-line arguments for [`get_user_balance`]
#[cfg(feature = "clap")]
#[derive(Debug, clap::Args)]
pub struct GetUserBalanceClapParams {
    /// The user's QCS id. May be found as `idpId` in the `AuthGetUser` API call.
    #[arg(long)]
    pub user_id: String,
}

#[cfg(feature = "clap")]
impl GetUserBalanceClapParams {
    pub async fn execute(
        self,
        configuration: &configuration::Configuration,
    ) -> Result<models::AccountBalance, miette::Error> {
        get_user_balance(configuration, self.user_id.as_str())
            .await
            .into_diagnostic()
    }
}

/// Serialize command-line arguments for [`get_user_billing_customer`]
#[cfg(feature = "clap")]
#[derive(Debug, clap::Args)]
pub struct GetUserBillingCustomerClapParams {
    /// The user's QCS id. May be found as `idpId` in the `AuthGetUser` API call.
    #[arg(long)]
    pub user_id: String,
}

#[cfg(feature = "clap")]
impl GetUserBillingCustomerClapParams {
    pub async fn execute(
        self,
        configuration: &configuration::Configuration,
    ) -> Result<models::BillingCustomer, miette::Error> {
        get_user_billing_customer(configuration, self.user_id.as_str())
            .await
            .into_diagnostic()
    }
}

/// Serialize command-line arguments for [`get_user_event_billing_price`]
#[cfg(feature = "clap")]
#[derive(Debug, clap::Args)]
pub struct GetUserEventBillingPriceClapParams {
    /// The user's QCS id. May be found as `idpId` in the `AuthGetUser` API call.
    #[arg(long)]
    pub user_id: String,
    pub get_account_event_billing_price_request:
        JsonMaybeStdin<crate::models::GetAccountEventBillingPriceRequest>,
}

#[cfg(feature = "clap")]
impl GetUserEventBillingPriceClapParams {
    pub async fn execute(
        self,
        configuration: &configuration::Configuration,
    ) -> Result<models::EventBillingPriceRate, miette::Error> {
        let request = self
            .get_account_event_billing_price_request
            .into_inner()
            .into_inner();

        get_user_event_billing_price(configuration, self.user_id.as_str(), request)
            .await
            .into_diagnostic()
    }
}

/// Serialize command-line arguments for [`get_user_upcoming_billing_invoice`]
#[cfg(feature = "clap")]
#[derive(Debug, clap::Args)]
pub struct GetUserUpcomingBillingInvoiceClapParams {
    /// The user's QCS id. May be found as `idpId` in the `AuthGetUser` API call.
    #[arg(long)]
    pub user_id: String,
}

#[cfg(feature = "clap")]
impl GetUserUpcomingBillingInvoiceClapParams {
    pub async fn execute(
        self,
        configuration: &configuration::Configuration,
    ) -> Result<models::BillingUpcomingInvoice, miette::Error> {
        get_user_upcoming_billing_invoice(configuration, self.user_id.as_str())
            .await
            .into_diagnostic()
    }
}

/// Serialize command-line arguments for [`get_viewer_user_onboarding_completed`]
#[cfg(feature = "clap")]
#[derive(Debug, clap::Args)]
pub struct GetViewerUserOnboardingCompletedClapParams {}

#[cfg(feature = "clap")]
impl GetViewerUserOnboardingCompletedClapParams {
    pub async fn execute(
        self,
        configuration: &configuration::Configuration,
    ) -> Result<models::ViewerUserOnboardingCompleted, miette::Error> {
        get_viewer_user_onboarding_completed(configuration)
            .await
            .into_diagnostic()
    }
}

/// Serialize command-line arguments for [`list_group_billing_invoice_lines`]
#[cfg(feature = "clap")]
#[derive(Debug, clap::Args)]
pub struct ListGroupBillingInvoiceLinesClapParams {
    /// URL-encoded name of group.
    #[arg(long)]
    pub group_name: String,
    /// URL-encoded billing invoice id.
    #[arg(long)]
    pub billing_invoice_id: String,
    /// An opaque token that can be appended to a request query to retrieve the next page of results. Empty if there are no more results to retrieve.
    #[arg(long)]
    pub page_token: Option<String>,
    #[arg(long)]
    pub page_size: Option<i64>,
}

#[cfg(feature = "clap")]
impl ListGroupBillingInvoiceLinesClapParams {
    pub async fn execute(
        self,
        configuration: &configuration::Configuration,
    ) -> Result<models::ListAccountBillingInvoiceLinesResponse, miette::Error> {
        list_group_billing_invoice_lines(
            configuration,
            self.group_name.as_str(),
            self.billing_invoice_id.as_str(),
            self.page_token.as_deref(),
            self.page_size,
        )
        .await
        .into_diagnostic()
    }
}

/// Serialize command-line arguments for [`list_group_billing_invoices`]
#[cfg(feature = "clap")]
#[derive(Debug, clap::Args)]
pub struct ListGroupBillingInvoicesClapParams {
    /// URL-encoded name of group.
    #[arg(long)]
    pub group_name: String,
    /// An opaque token that can be appended to a request query to retrieve the next page of results. Empty if there are no more results to retrieve.
    #[arg(long)]
    pub page_token: Option<String>,
    #[arg(long)]
    pub page_size: Option<i64>,
}

#[cfg(feature = "clap")]
impl ListGroupBillingInvoicesClapParams {
    pub async fn execute(
        self,
        configuration: &configuration::Configuration,
    ) -> Result<models::ListAccountBillingInvoicesResponse, miette::Error> {
        list_group_billing_invoices(
            configuration,
            self.group_name.as_str(),
            self.page_token.as_deref(),
            self.page_size,
        )
        .await
        .into_diagnostic()
    }
}

/// Serialize command-line arguments for [`list_group_upcoming_billing_invoice_lines`]
#[cfg(feature = "clap")]
#[derive(Debug, clap::Args)]
pub struct ListGroupUpcomingBillingInvoiceLinesClapParams {
    /// URL-encoded name of group.
    #[arg(long)]
    pub group_name: String,
    /// An opaque token that can be appended to a request query to retrieve the next page of results. Empty if there are no more results to retrieve.
    #[arg(long)]
    pub page_token: Option<String>,
    #[arg(long)]
    pub page_size: Option<i64>,
}

#[cfg(feature = "clap")]
impl ListGroupUpcomingBillingInvoiceLinesClapParams {
    pub async fn execute(
        self,
        configuration: &configuration::Configuration,
    ) -> Result<models::ListAccountBillingInvoiceLinesResponse, miette::Error> {
        list_group_upcoming_billing_invoice_lines(
            configuration,
            self.group_name.as_str(),
            self.page_token.as_deref(),
            self.page_size,
        )
        .await
        .into_diagnostic()
    }
}

/// Serialize command-line arguments for [`list_group_users`]
#[cfg(feature = "clap")]
#[derive(Debug, clap::Args)]
pub struct ListGroupUsersClapParams {
    /// URL encoded name of group for which to retrieve users.
    #[arg(long)]
    pub group_name: String,
    #[arg(long)]
    pub page_size: Option<i64>,
    /// An opaque token that can be appended to a request query to retrieve the next page of results. Empty if there are no more results to retrieve.
    #[arg(long)]
    pub page_token: Option<String>,
}

#[cfg(feature = "clap")]
impl ListGroupUsersClapParams {
    pub async fn execute(
        self,
        configuration: &configuration::Configuration,
    ) -> Result<models::ListGroupUsersResponse, miette::Error> {
        list_group_users(
            configuration,
            self.group_name.as_str(),
            self.page_size,
            self.page_token.as_deref(),
        )
        .await
        .into_diagnostic()
    }
}

/// Serialize command-line arguments for [`list_user_billing_invoice_lines`]
#[cfg(feature = "clap")]
#[derive(Debug, clap::Args)]
pub struct ListUserBillingInvoiceLinesClapParams {
    /// URL-encoded QCS id of user. May be found as `idpId` in the `AuthGetUser` API call.
    #[arg(long)]
    pub user_id: String,
    /// URL-encoded billing invoice id.
    #[arg(long)]
    pub billing_invoice_id: String,
    /// An opaque token that can be appended to a request query to retrieve the next page of results. Empty if there are no more results to retrieve.
    #[arg(long)]
    pub page_token: Option<String>,
    #[arg(long)]
    pub page_size: Option<i64>,
}

#[cfg(feature = "clap")]
impl ListUserBillingInvoiceLinesClapParams {
    pub async fn execute(
        self,
        configuration: &configuration::Configuration,
    ) -> Result<models::ListAccountBillingInvoiceLinesResponse, miette::Error> {
        list_user_billing_invoice_lines(
            configuration,
            self.user_id.as_str(),
            self.billing_invoice_id.as_str(),
            self.page_token.as_deref(),
            self.page_size,
        )
        .await
        .into_diagnostic()
    }
}

/// Serialize command-line arguments for [`list_user_billing_invoices`]
#[cfg(feature = "clap")]
#[derive(Debug, clap::Args)]
pub struct ListUserBillingInvoicesClapParams {
    /// The user's QCS id. May be found as `idpId` in the `AuthGetUser` API call.
    #[arg(long)]
    pub user_id: String,
    /// An opaque token that can be appended to a request query to retrieve the next page of results. Empty if there are no more results to retrieve.
    #[arg(long)]
    pub page_token: Option<String>,
    #[arg(long)]
    pub page_size: Option<i64>,
}

#[cfg(feature = "clap")]
impl ListUserBillingInvoicesClapParams {
    pub async fn execute(
        self,
        configuration: &configuration::Configuration,
    ) -> Result<models::ListAccountBillingInvoicesResponse, miette::Error> {
        list_user_billing_invoices(
            configuration,
            self.user_id.as_str(),
            self.page_token.as_deref(),
            self.page_size,
        )
        .await
        .into_diagnostic()
    }
}

/// Serialize command-line arguments for [`list_user_groups`]
#[cfg(feature = "clap")]
#[derive(Debug, clap::Args)]
pub struct ListUserGroupsClapParams {
    /// The user's QCS id. May be found as `idpId` in the `AuthGetUser` API call.
    #[arg(long)]
    pub user_id: String,
    #[arg(long)]
    pub page_size: Option<i64>,
    /// An opaque token that can be appended to a request query to retrieve the next page of results. Empty if there are no more results to retrieve.
    #[arg(long)]
    pub page_token: Option<String>,
}

#[cfg(feature = "clap")]
impl ListUserGroupsClapParams {
    pub async fn execute(
        self,
        configuration: &configuration::Configuration,
    ) -> Result<models::ListGroupsResponse, miette::Error> {
        list_user_groups(
            configuration,
            self.user_id.as_str(),
            self.page_size,
            self.page_token.as_deref(),
        )
        .await
        .into_diagnostic()
    }
}

/// Serialize command-line arguments for [`list_user_upcoming_billing_invoice_lines`]
#[cfg(feature = "clap")]
#[derive(Debug, clap::Args)]
pub struct ListUserUpcomingBillingInvoiceLinesClapParams {
    /// The user's QCS id. May be found as `idpId` in the `AuthGetUser` API call.
    #[arg(long)]
    pub user_id: String,
    /// An opaque token that can be appended to a request query to retrieve the next page of results. Empty if there are no more results to retrieve.
    #[arg(long)]
    pub page_token: Option<String>,
    #[arg(long)]
    pub page_size: Option<i64>,
}

#[cfg(feature = "clap")]
impl ListUserUpcomingBillingInvoiceLinesClapParams {
    pub async fn execute(
        self,
        configuration: &configuration::Configuration,
    ) -> Result<models::ListAccountBillingInvoiceLinesResponse, miette::Error> {
        list_user_upcoming_billing_invoice_lines(
            configuration,
            self.user_id.as_str(),
            self.page_token.as_deref(),
            self.page_size,
        )
        .await
        .into_diagnostic()
    }
}

/// Serialize command-line arguments for [`list_viewer_announcements`]
#[cfg(feature = "clap")]
#[derive(Debug, clap::Args)]
pub struct ListViewerAnnouncementsClapParams {
    #[arg(long)]
    pub page_size: Option<i64>,
    /// An opaque token that can be appended to a request query to retrieve the next page of results. Empty if there are no more results to retrieve.
    #[arg(long)]
    pub page_token: Option<String>,
    /// Include dismissed announcements in the response.
    #[arg(long)]
    pub include_dismissed: Option<bool>,
}

#[cfg(feature = "clap")]
impl ListViewerAnnouncementsClapParams {
    pub async fn execute(
        self,
        configuration: &configuration::Configuration,
    ) -> Result<models::AnnouncementsResponse, miette::Error> {
        list_viewer_announcements(
            configuration,
            self.page_size,
            self.page_token.as_deref(),
            self.include_dismissed,
        )
        .await
        .into_diagnostic()
    }
}

/// Serialize command-line arguments for [`put_viewer_user_onboarding_completed`]
#[cfg(feature = "clap")]
#[derive(Debug, clap::Args)]
pub struct PutViewerUserOnboardingCompletedClapParams {
    pub viewer_user_onboarding_completed:
        Option<JsonMaybeStdin<crate::models::ViewerUserOnboardingCompleted>>,
}

#[cfg(feature = "clap")]
impl PutViewerUserOnboardingCompletedClapParams {
    pub async fn execute(
        self,
        configuration: &configuration::Configuration,
    ) -> Result<models::ViewerUserOnboardingCompleted, miette::Error> {
        let request = self
            .viewer_user_onboarding_completed
            .map(|body| body.into_inner().into_inner());

        put_viewer_user_onboarding_completed(configuration, request)
            .await
            .into_diagnostic()
    }
}

/// Serialize command-line arguments for [`remove_group_user`]
#[cfg(feature = "clap")]
#[derive(Debug, clap::Args)]
pub struct RemoveGroupUserClapParams {
    pub remove_group_user_request: JsonMaybeStdin<crate::models::RemoveGroupUserRequest>,
}

#[cfg(feature = "clap")]
impl RemoveGroupUserClapParams {
    pub async fn execute(
        self,
        configuration: &configuration::Configuration,
    ) -> Result<(), miette::Error> {
        let request = self.remove_group_user_request.into_inner().into_inner();

        remove_group_user(configuration, request)
            .await
            .into_diagnostic()
    }
}

/// Serialize command-line arguments for [`update_viewer_user_profile`]
#[cfg(feature = "clap")]
#[derive(Debug, clap::Args)]
pub struct UpdateViewerUserProfileClapParams {
    pub update_viewer_user_profile_request:
        JsonMaybeStdin<crate::models::UpdateViewerUserProfileRequest>,
}

#[cfg(feature = "clap")]
impl UpdateViewerUserProfileClapParams {
    pub async fn execute(
        self,
        configuration: &configuration::Configuration,
    ) -> Result<models::User, miette::Error> {
        let request = self
            .update_viewer_user_profile_request
            .into_inner()
            .into_inner();

        update_viewer_user_profile(configuration, request)
            .await
            .into_diagnostic()
    }
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

async fn activate_user_inner(
    configuration: &configuration::Configuration,
    backoff: &mut ExponentialBackoff,
    activate_user_request: Option<crate::models::ActivateUserRequest>,
) -> Result<models::User, Error<ActivateUserError>> {
    let local_var_configuration = configuration;
    // add a prefix to parameters to efficiently prevent name collisions
    let p_body_activate_user_request = activate_user_request;

    let local_var_client = &local_var_configuration.client;

    let local_var_uri_str = format!(
        "{}/v1/users:activate",
        local_var_configuration.qcs_config.api_url()
    );
    let mut local_var_req_builder =
        local_var_client.request(reqwest::Method::POST, local_var_uri_str.as_str());

    #[cfg(feature = "tracing")]
    {
        // Ignore parsing errors if the URL is invalid for some reason.
        // If it is invalid, it will turn up as an error later when actually making the request.
        let local_var_do_tracing = local_var_uri_str
            .parse::<::url::Url>()
            .ok()
            .is_none_or(|url| {
                configuration
                    .qcs_config
                    .should_trace(&::urlpattern::UrlPatternMatchInput::Url(url))
            });

        if local_var_do_tracing {
            ::tracing::debug!(
                url=%local_var_uri_str,
                method="POST",
                "making activate_user request",
            );
        }
    }

    // Use the QCS Bearer token if a client OAuthSession is present,
    // but do not require one when the security schema says it is optional.
    {
        use qcs_api_client_common::configuration::TokenError;

        #[allow(
            clippy::nonminimal_bool,
            clippy::eq_op,
            reason = "Logic must be done at runtime since it cannot be handled by the mustache template engine."
        )]
        let is_jwt_bearer_optional: bool = false;

        let token = local_var_configuration
            .qcs_config
            .get_bearer_access_token()
            .await;

        if is_jwt_bearer_optional && matches!(token, Err(TokenError::NoCredentials)) {
            // the client is configured without any OAuthSession, but this call does not require one.
            #[cfg(feature = "tracing")]
            tracing::debug!(
                "No client credentials found, but this call does not require authentication."
            );
        } else {
            local_var_req_builder = local_var_req_builder.bearer_auth(token?.secret());
        }
    }

    local_var_req_builder = local_var_req_builder.json(&p_body_activate_user_request);

    let local_var_req = local_var_req_builder.build()?;
    let local_var_resp = local_var_client.execute(local_var_req).await?;

    let local_var_status = local_var_resp.status();
    let local_var_raw_content_type = local_var_resp
        .headers()
        .get("content-type")
        .and_then(|v| v.to_str().ok())
        .unwrap_or("application/octet-stream")
        .to_string();
    let local_var_content_type = super::ContentType::from(local_var_raw_content_type.as_str());

    if !local_var_status.is_client_error() && !local_var_status.is_server_error() {
        let local_var_content = local_var_resp.text().await?;
        match local_var_content_type {
            ContentType::Json => serde_path_to_error::deserialize(
                &mut serde_json::Deserializer::from_str(&local_var_content),
            )
            .map_err(Error::from),
            ContentType::Text => Err(Error::InvalidContentType {
                content_type: local_var_raw_content_type,
                return_type: "models::User",
            }),
            ContentType::Unsupported(unknown_type) => Err(Error::InvalidContentType {
                content_type: unknown_type,
                return_type: "models::User",
            }),
        }
    } else {
        let local_var_retry_delay =
            duration_from_response(local_var_resp.status(), local_var_resp.headers(), backoff);
        let local_var_content = local_var_resp.text().await?;
        let local_var_entity: Option<ActivateUserError> =
            serde_json::from_str(&local_var_content).ok();
        let local_var_error = ResponseContent {
            status: local_var_status,
            content: local_var_content,
            entity: local_var_entity,
            retry_delay: local_var_retry_delay,
        };
        Err(Error::ResponseError(local_var_error))
    }
}

/// Activate a user, completing an invitation request.
pub async fn activate_user(
    configuration: &configuration::Configuration,
    activate_user_request: Option<crate::models::ActivateUserRequest>,
) -> Result<models::User, Error<ActivateUserError>> {
    let mut backoff = configuration.backoff.clone();
    let mut refreshed_credentials = false;
    let method = reqwest::Method::POST;
    loop {
        let result =
            activate_user_inner(configuration, &mut backoff, activate_user_request.clone()).await;

        match result {
            Ok(result) => return Ok(result),
            Err(Error::ResponseError(response)) => {
                if !refreshed_credentials
                    && matches!(
                        response.status,
                        StatusCode::FORBIDDEN | StatusCode::UNAUTHORIZED
                    )
                {
                    configuration.qcs_config.refresh().await?;
                    refreshed_credentials = true;
                    continue;
                } else if let Some(duration) = response.retry_delay {
                    tokio::time::sleep(duration).await;
                    continue;
                }

                return Err(Error::ResponseError(response));
            }
            Err(Error::Reqwest(error)) => {
                if let Some(duration) = duration_from_reqwest_error(&method, &error, &mut backoff) {
                    tokio::time::sleep(duration).await;
                    continue;
                }

                return Err(Error::Reqwest(error));
            }
            Err(Error::Io(error)) => {
                if let Some(duration) = duration_from_io_error(&method, &error, &mut backoff) {
                    tokio::time::sleep(duration).await;
                    continue;
                }

                return Err(Error::Io(error));
            }
            Err(error) => return Err(error),
        }
    }
}
async fn add_group_user_inner(
    configuration: &configuration::Configuration,
    backoff: &mut ExponentialBackoff,
    add_group_user_request: crate::models::AddGroupUserRequest,
) -> Result<(), Error<AddGroupUserError>> {
    let local_var_configuration = configuration;
    // add a prefix to parameters to efficiently prevent name collisions
    let p_body_add_group_user_request = add_group_user_request;

    let local_var_client = &local_var_configuration.client;

    let local_var_uri_str = format!(
        "{}/v1/groups:addUser",
        local_var_configuration.qcs_config.api_url()
    );
    let mut local_var_req_builder =
        local_var_client.request(reqwest::Method::POST, local_var_uri_str.as_str());

    #[cfg(feature = "tracing")]
    {
        // Ignore parsing errors if the URL is invalid for some reason.
        // If it is invalid, it will turn up as an error later when actually making the request.
        let local_var_do_tracing = local_var_uri_str
            .parse::<::url::Url>()
            .ok()
            .is_none_or(|url| {
                configuration
                    .qcs_config
                    .should_trace(&::urlpattern::UrlPatternMatchInput::Url(url))
            });

        if local_var_do_tracing {
            ::tracing::debug!(
                url=%local_var_uri_str,
                method="POST",
                "making add_group_user request",
            );
        }
    }

    // Use the QCS Bearer token if a client OAuthSession is present,
    // but do not require one when the security schema says it is optional.
    {
        use qcs_api_client_common::configuration::TokenError;

        #[allow(
            clippy::nonminimal_bool,
            clippy::eq_op,
            reason = "Logic must be done at runtime since it cannot be handled by the mustache template engine."
        )]
        let is_jwt_bearer_optional: bool = false || "JWTBearer" == "JWTBearerOptional";

        let token = local_var_configuration
            .qcs_config
            .get_bearer_access_token()
            .await;

        if is_jwt_bearer_optional && matches!(token, Err(TokenError::NoCredentials)) {
            // the client is configured without any OAuthSession, but this call does not require one.
            #[cfg(feature = "tracing")]
            tracing::debug!(
                "No client credentials found, but this call does not require authentication."
            );
        } else {
            local_var_req_builder = local_var_req_builder.bearer_auth(token?.secret());
        }
    }

    local_var_req_builder = local_var_req_builder.json(&p_body_add_group_user_request);

    let local_var_req = local_var_req_builder.build()?;
    let local_var_resp = local_var_client.execute(local_var_req).await?;

    let local_var_status = local_var_resp.status();

    if !local_var_status.is_client_error() && !local_var_status.is_server_error() {
        Ok(())
    } else {
        let local_var_retry_delay =
            duration_from_response(local_var_resp.status(), local_var_resp.headers(), backoff);
        let local_var_content = local_var_resp.text().await?;
        let local_var_entity: Option<AddGroupUserError> =
            serde_json::from_str(&local_var_content).ok();
        let local_var_error = ResponseContent {
            status: local_var_status,
            content: local_var_content,
            entity: local_var_entity,
            retry_delay: local_var_retry_delay,
        };
        Err(Error::ResponseError(local_var_error))
    }
}

/// Add a user to a group. Note, group membership may take several minutes to update within our identity provider. After adding a user to a group, please allow up to 60 minutes for changes to be reflected.
pub async fn add_group_user(
    configuration: &configuration::Configuration,
    add_group_user_request: crate::models::AddGroupUserRequest,
) -> Result<(), Error<AddGroupUserError>> {
    let mut backoff = configuration.backoff.clone();
    let mut refreshed_credentials = false;
    let method = reqwest::Method::POST;
    loop {
        let result =
            add_group_user_inner(configuration, &mut backoff, add_group_user_request.clone()).await;

        match result {
            Ok(result) => return Ok(result),
            Err(Error::ResponseError(response)) => {
                if !refreshed_credentials
                    && matches!(
                        response.status,
                        StatusCode::FORBIDDEN | StatusCode::UNAUTHORIZED
                    )
                {
                    configuration.qcs_config.refresh().await?;
                    refreshed_credentials = true;
                    continue;
                } else if let Some(duration) = response.retry_delay {
                    tokio::time::sleep(duration).await;
                    continue;
                }

                return Err(Error::ResponseError(response));
            }
            Err(Error::Reqwest(error)) => {
                if let Some(duration) = duration_from_reqwest_error(&method, &error, &mut backoff) {
                    tokio::time::sleep(duration).await;
                    continue;
                }

                return Err(Error::Reqwest(error));
            }
            Err(Error::Io(error)) => {
                if let Some(duration) = duration_from_io_error(&method, &error, &mut backoff) {
                    tokio::time::sleep(duration).await;
                    continue;
                }

                return Err(Error::Io(error));
            }
            Err(error) => return Err(error),
        }
    }
}
async fn dismiss_viewer_announcement_inner(
    configuration: &configuration::Configuration,
    backoff: &mut ExponentialBackoff,
    announcement_id: i64,
) -> Result<(), Error<DismissViewerAnnouncementError>> {
    let local_var_configuration = configuration;
    // add a prefix to parameters to efficiently prevent name collisions
    let p_path_announcement_id = announcement_id;

    let local_var_client = &local_var_configuration.client;

    let local_var_uri_str = format!(
        "{}/v1/viewer/announcements/{announcementId}",
        local_var_configuration.qcs_config.api_url(),
        announcementId = p_path_announcement_id
    );
    let mut local_var_req_builder =
        local_var_client.request(reqwest::Method::DELETE, local_var_uri_str.as_str());

    #[cfg(feature = "tracing")]
    {
        // Ignore parsing errors if the URL is invalid for some reason.
        // If it is invalid, it will turn up as an error later when actually making the request.
        let local_var_do_tracing = local_var_uri_str
            .parse::<::url::Url>()
            .ok()
            .is_none_or(|url| {
                configuration
                    .qcs_config
                    .should_trace(&::urlpattern::UrlPatternMatchInput::Url(url))
            });

        if local_var_do_tracing {
            ::tracing::debug!(
                url=%local_var_uri_str,
                method="DELETE",
                "making dismiss_viewer_announcement request",
            );
        }
    }

    // Use the QCS Bearer token if a client OAuthSession is present,
    // but do not require one when the security schema says it is optional.
    {
        use qcs_api_client_common::configuration::TokenError;

        #[allow(
            clippy::nonminimal_bool,
            clippy::eq_op,
            reason = "Logic must be done at runtime since it cannot be handled by the mustache template engine."
        )]
        let is_jwt_bearer_optional: bool = false || "JWTBearer" == "JWTBearerOptional";

        let token = local_var_configuration
            .qcs_config
            .get_bearer_access_token()
            .await;

        if is_jwt_bearer_optional && matches!(token, Err(TokenError::NoCredentials)) {
            // the client is configured without any OAuthSession, but this call does not require one.
            #[cfg(feature = "tracing")]
            tracing::debug!(
                "No client credentials found, but this call does not require authentication."
            );
        } else {
            local_var_req_builder = local_var_req_builder.bearer_auth(token?.secret());
        }
    }

    let local_var_req = local_var_req_builder.build()?;
    let local_var_resp = local_var_client.execute(local_var_req).await?;

    let local_var_status = local_var_resp.status();

    if !local_var_status.is_client_error() && !local_var_status.is_server_error() {
        Ok(())
    } else {
        let local_var_retry_delay =
            duration_from_response(local_var_resp.status(), local_var_resp.headers(), backoff);
        let local_var_content = local_var_resp.text().await?;
        let local_var_entity: Option<DismissViewerAnnouncementError> =
            serde_json::from_str(&local_var_content).ok();
        let local_var_error = ResponseContent {
            status: local_var_status,
            content: local_var_content,
            entity: local_var_entity,
            retry_delay: local_var_retry_delay,
        };
        Err(Error::ResponseError(local_var_error))
    }
}

/// Dismiss an announcement for an authenticating user, indicating that they do not want to see it again.
pub async fn dismiss_viewer_announcement(
    configuration: &configuration::Configuration,
    announcement_id: i64,
) -> Result<(), Error<DismissViewerAnnouncementError>> {
    let mut backoff = configuration.backoff.clone();
    let mut refreshed_credentials = false;
    let method = reqwest::Method::DELETE;
    loop {
        let result =
            dismiss_viewer_announcement_inner(configuration, &mut backoff, announcement_id.clone())
                .await;

        match result {
            Ok(result) => return Ok(result),
            Err(Error::ResponseError(response)) => {
                if !refreshed_credentials
                    && matches!(
                        response.status,
                        StatusCode::FORBIDDEN | StatusCode::UNAUTHORIZED
                    )
                {
                    configuration.qcs_config.refresh().await?;
                    refreshed_credentials = true;
                    continue;
                } else if let Some(duration) = response.retry_delay {
                    tokio::time::sleep(duration).await;
                    continue;
                }

                return Err(Error::ResponseError(response));
            }
            Err(Error::Reqwest(error)) => {
                if let Some(duration) = duration_from_reqwest_error(&method, &error, &mut backoff) {
                    tokio::time::sleep(duration).await;
                    continue;
                }

                return Err(Error::Reqwest(error));
            }
            Err(Error::Io(error)) => {
                if let Some(duration) = duration_from_io_error(&method, &error, &mut backoff) {
                    tokio::time::sleep(duration).await;
                    continue;
                }

                return Err(Error::Io(error));
            }
            Err(error) => return Err(error),
        }
    }
}
async fn get_group_balance_inner(
    configuration: &configuration::Configuration,
    backoff: &mut ExponentialBackoff,
    group_name: &str,
) -> Result<models::AccountBalance, Error<GetGroupBalanceError>> {
    let local_var_configuration = configuration;
    // add a prefix to parameters to efficiently prevent name collisions
    let p_path_group_name = group_name;

    let local_var_client = &local_var_configuration.client;

    let local_var_uri_str = format!(
        "{}/v1/groups/{groupName}/balance",
        local_var_configuration.qcs_config.api_url(),
        groupName = crate::apis::urlencode(p_path_group_name)
    );
    let mut local_var_req_builder =
        local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str());

    #[cfg(feature = "tracing")]
    {
        // Ignore parsing errors if the URL is invalid for some reason.
        // If it is invalid, it will turn up as an error later when actually making the request.
        let local_var_do_tracing = local_var_uri_str
            .parse::<::url::Url>()
            .ok()
            .is_none_or(|url| {
                configuration
                    .qcs_config
                    .should_trace(&::urlpattern::UrlPatternMatchInput::Url(url))
            });

        if local_var_do_tracing {
            ::tracing::debug!(
                url=%local_var_uri_str,
                method="GET",
                "making get_group_balance request",
            );
        }
    }

    // Use the QCS Bearer token if a client OAuthSession is present,
    // but do not require one when the security schema says it is optional.
    {
        use qcs_api_client_common::configuration::TokenError;

        #[allow(
            clippy::nonminimal_bool,
            clippy::eq_op,
            reason = "Logic must be done at runtime since it cannot be handled by the mustache template engine."
        )]
        let is_jwt_bearer_optional: bool = false || "JWTBearer" == "JWTBearerOptional";

        let token = local_var_configuration
            .qcs_config
            .get_bearer_access_token()
            .await;

        if is_jwt_bearer_optional && matches!(token, Err(TokenError::NoCredentials)) {
            // the client is configured without any OAuthSession, but this call does not require one.
            #[cfg(feature = "tracing")]
            tracing::debug!(
                "No client credentials found, but this call does not require authentication."
            );
        } else {
            local_var_req_builder = local_var_req_builder.bearer_auth(token?.secret());
        }
    }

    let local_var_req = local_var_req_builder.build()?;
    let local_var_resp = local_var_client.execute(local_var_req).await?;

    let local_var_status = local_var_resp.status();
    let local_var_raw_content_type = local_var_resp
        .headers()
        .get("content-type")
        .and_then(|v| v.to_str().ok())
        .unwrap_or("application/octet-stream")
        .to_string();
    let local_var_content_type = super::ContentType::from(local_var_raw_content_type.as_str());

    if !local_var_status.is_client_error() && !local_var_status.is_server_error() {
        let local_var_content = local_var_resp.text().await?;
        match local_var_content_type {
            ContentType::Json => serde_path_to_error::deserialize(
                &mut serde_json::Deserializer::from_str(&local_var_content),
            )
            .map_err(Error::from),
            ContentType::Text => Err(Error::InvalidContentType {
                content_type: local_var_raw_content_type,
                return_type: "models::AccountBalance",
            }),
            ContentType::Unsupported(unknown_type) => Err(Error::InvalidContentType {
                content_type: unknown_type,
                return_type: "models::AccountBalance",
            }),
        }
    } else {
        let local_var_retry_delay =
            duration_from_response(local_var_resp.status(), local_var_resp.headers(), backoff);
        let local_var_content = local_var_resp.text().await?;
        let local_var_entity: Option<GetGroupBalanceError> =
            serde_json::from_str(&local_var_content).ok();
        let local_var_error = ResponseContent {
            status: local_var_status,
            content: local_var_content,
            entity: local_var_entity,
            retry_delay: local_var_retry_delay,
        };
        Err(Error::ResponseError(local_var_error))
    }
}

/// Retrieve the balance of the requested QCS group account.
pub async fn get_group_balance(
    configuration: &configuration::Configuration,
    group_name: &str,
) -> Result<models::AccountBalance, Error<GetGroupBalanceError>> {
    let mut backoff = configuration.backoff.clone();
    let mut refreshed_credentials = false;
    let method = reqwest::Method::GET;
    loop {
        let result = get_group_balance_inner(configuration, &mut backoff, group_name.clone()).await;

        match result {
            Ok(result) => return Ok(result),
            Err(Error::ResponseError(response)) => {
                if !refreshed_credentials
                    && matches!(
                        response.status,
                        StatusCode::FORBIDDEN | StatusCode::UNAUTHORIZED
                    )
                {
                    configuration.qcs_config.refresh().await?;
                    refreshed_credentials = true;
                    continue;
                } else if let Some(duration) = response.retry_delay {
                    tokio::time::sleep(duration).await;
                    continue;
                }

                return Err(Error::ResponseError(response));
            }
            Err(Error::Reqwest(error)) => {
                if let Some(duration) = duration_from_reqwest_error(&method, &error, &mut backoff) {
                    tokio::time::sleep(duration).await;
                    continue;
                }

                return Err(Error::Reqwest(error));
            }
            Err(Error::Io(error)) => {
                if let Some(duration) = duration_from_io_error(&method, &error, &mut backoff) {
                    tokio::time::sleep(duration).await;
                    continue;
                }

                return Err(Error::Io(error));
            }
            Err(error) => return Err(error),
        }
    }
}
async fn get_group_billing_customer_inner(
    configuration: &configuration::Configuration,
    backoff: &mut ExponentialBackoff,
    group_name: &str,
) -> Result<models::BillingCustomer, Error<GetGroupBillingCustomerError>> {
    let local_var_configuration = configuration;
    // add a prefix to parameters to efficiently prevent name collisions
    let p_path_group_name = group_name;

    let local_var_client = &local_var_configuration.client;

    let local_var_uri_str = format!(
        "{}/v1/groups/{groupName}/billingCustomer",
        local_var_configuration.qcs_config.api_url(),
        groupName = crate::apis::urlencode(p_path_group_name)
    );
    let mut local_var_req_builder =
        local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str());

    #[cfg(feature = "tracing")]
    {
        // Ignore parsing errors if the URL is invalid for some reason.
        // If it is invalid, it will turn up as an error later when actually making the request.
        let local_var_do_tracing = local_var_uri_str
            .parse::<::url::Url>()
            .ok()
            .is_none_or(|url| {
                configuration
                    .qcs_config
                    .should_trace(&::urlpattern::UrlPatternMatchInput::Url(url))
            });

        if local_var_do_tracing {
            ::tracing::debug!(
                url=%local_var_uri_str,
                method="GET",
                "making get_group_billing_customer request",
            );
        }
    }

    // Use the QCS Bearer token if a client OAuthSession is present,
    // but do not require one when the security schema says it is optional.
    {
        use qcs_api_client_common::configuration::TokenError;

        #[allow(
            clippy::nonminimal_bool,
            clippy::eq_op,
            reason = "Logic must be done at runtime since it cannot be handled by the mustache template engine."
        )]
        let is_jwt_bearer_optional: bool = false || "JWTBearer" == "JWTBearerOptional";

        let token = local_var_configuration
            .qcs_config
            .get_bearer_access_token()
            .await;

        if is_jwt_bearer_optional && matches!(token, Err(TokenError::NoCredentials)) {
            // the client is configured without any OAuthSession, but this call does not require one.
            #[cfg(feature = "tracing")]
            tracing::debug!(
                "No client credentials found, but this call does not require authentication."
            );
        } else {
            local_var_req_builder = local_var_req_builder.bearer_auth(token?.secret());
        }
    }

    let local_var_req = local_var_req_builder.build()?;
    let local_var_resp = local_var_client.execute(local_var_req).await?;

    let local_var_status = local_var_resp.status();
    let local_var_raw_content_type = local_var_resp
        .headers()
        .get("content-type")
        .and_then(|v| v.to_str().ok())
        .unwrap_or("application/octet-stream")
        .to_string();
    let local_var_content_type = super::ContentType::from(local_var_raw_content_type.as_str());

    if !local_var_status.is_client_error() && !local_var_status.is_server_error() {
        let local_var_content = local_var_resp.text().await?;
        match local_var_content_type {
            ContentType::Json => serde_path_to_error::deserialize(
                &mut serde_json::Deserializer::from_str(&local_var_content),
            )
            .map_err(Error::from),
            ContentType::Text => Err(Error::InvalidContentType {
                content_type: local_var_raw_content_type,
                return_type: "models::BillingCustomer",
            }),
            ContentType::Unsupported(unknown_type) => Err(Error::InvalidContentType {
                content_type: unknown_type,
                return_type: "models::BillingCustomer",
            }),
        }
    } else {
        let local_var_retry_delay =
            duration_from_response(local_var_resp.status(), local_var_resp.headers(), backoff);
        let local_var_content = local_var_resp.text().await?;
        let local_var_entity: Option<GetGroupBillingCustomerError> =
            serde_json::from_str(&local_var_content).ok();
        let local_var_error = ResponseContent {
            status: local_var_status,
            content: local_var_content,
            entity: local_var_entity,
            retry_delay: local_var_retry_delay,
        };
        Err(Error::ResponseError(local_var_error))
    }
}

/// Retrieve billing customer for a QCS group account.
pub async fn get_group_billing_customer(
    configuration: &configuration::Configuration,
    group_name: &str,
) -> Result<models::BillingCustomer, Error<GetGroupBillingCustomerError>> {
    let mut backoff = configuration.backoff.clone();
    let mut refreshed_credentials = false;
    let method = reqwest::Method::GET;
    loop {
        let result =
            get_group_billing_customer_inner(configuration, &mut backoff, group_name.clone()).await;

        match result {
            Ok(result) => return Ok(result),
            Err(Error::ResponseError(response)) => {
                if !refreshed_credentials
                    && matches!(
                        response.status,
                        StatusCode::FORBIDDEN | StatusCode::UNAUTHORIZED
                    )
                {
                    configuration.qcs_config.refresh().await?;
                    refreshed_credentials = true;
                    continue;
                } else if let Some(duration) = response.retry_delay {
                    tokio::time::sleep(duration).await;
                    continue;
                }

                return Err(Error::ResponseError(response));
            }
            Err(Error::Reqwest(error)) => {
                if let Some(duration) = duration_from_reqwest_error(&method, &error, &mut backoff) {
                    tokio::time::sleep(duration).await;
                    continue;
                }

                return Err(Error::Reqwest(error));
            }
            Err(Error::Io(error)) => {
                if let Some(duration) = duration_from_io_error(&method, &error, &mut backoff) {
                    tokio::time::sleep(duration).await;
                    continue;
                }

                return Err(Error::Io(error));
            }
            Err(error) => return Err(error),
        }
    }
}
async fn get_group_upcoming_billing_invoice_inner(
    configuration: &configuration::Configuration,
    backoff: &mut ExponentialBackoff,
    group_name: &str,
) -> Result<models::BillingUpcomingInvoice, Error<GetGroupUpcomingBillingInvoiceError>> {
    let local_var_configuration = configuration;
    // add a prefix to parameters to efficiently prevent name collisions
    let p_path_group_name = group_name;

    let local_var_client = &local_var_configuration.client;

    let local_var_uri_str = format!(
        "{}/v1/groups/{groupName}/billingInvoices:getUpcoming",
        local_var_configuration.qcs_config.api_url(),
        groupName = crate::apis::urlencode(p_path_group_name)
    );
    let mut local_var_req_builder =
        local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str());

    #[cfg(feature = "tracing")]
    {
        // Ignore parsing errors if the URL is invalid for some reason.
        // If it is invalid, it will turn up as an error later when actually making the request.
        let local_var_do_tracing = local_var_uri_str
            .parse::<::url::Url>()
            .ok()
            .is_none_or(|url| {
                configuration
                    .qcs_config
                    .should_trace(&::urlpattern::UrlPatternMatchInput::Url(url))
            });

        if local_var_do_tracing {
            ::tracing::debug!(
                url=%local_var_uri_str,
                method="GET",
                "making get_group_upcoming_billing_invoice request",
            );
        }
    }

    // Use the QCS Bearer token if a client OAuthSession is present,
    // but do not require one when the security schema says it is optional.
    {
        use qcs_api_client_common::configuration::TokenError;

        #[allow(
            clippy::nonminimal_bool,
            clippy::eq_op,
            reason = "Logic must be done at runtime since it cannot be handled by the mustache template engine."
        )]
        let is_jwt_bearer_optional: bool = false || "JWTBearer" == "JWTBearerOptional";

        let token = local_var_configuration
            .qcs_config
            .get_bearer_access_token()
            .await;

        if is_jwt_bearer_optional && matches!(token, Err(TokenError::NoCredentials)) {
            // the client is configured without any OAuthSession, but this call does not require one.
            #[cfg(feature = "tracing")]
            tracing::debug!(
                "No client credentials found, but this call does not require authentication."
            );
        } else {
            local_var_req_builder = local_var_req_builder.bearer_auth(token?.secret());
        }
    }

    let local_var_req = local_var_req_builder.build()?;
    let local_var_resp = local_var_client.execute(local_var_req).await?;

    let local_var_status = local_var_resp.status();
    let local_var_raw_content_type = local_var_resp
        .headers()
        .get("content-type")
        .and_then(|v| v.to_str().ok())
        .unwrap_or("application/octet-stream")
        .to_string();
    let local_var_content_type = super::ContentType::from(local_var_raw_content_type.as_str());

    if !local_var_status.is_client_error() && !local_var_status.is_server_error() {
        let local_var_content = local_var_resp.text().await?;
        match local_var_content_type {
            ContentType::Json => serde_path_to_error::deserialize(
                &mut serde_json::Deserializer::from_str(&local_var_content),
            )
            .map_err(Error::from),
            ContentType::Text => Err(Error::InvalidContentType {
                content_type: local_var_raw_content_type,
                return_type: "models::BillingUpcomingInvoice",
            }),
            ContentType::Unsupported(unknown_type) => Err(Error::InvalidContentType {
                content_type: unknown_type,
                return_type: "models::BillingUpcomingInvoice",
            }),
        }
    } else {
        let local_var_retry_delay =
            duration_from_response(local_var_resp.status(), local_var_resp.headers(), backoff);
        let local_var_content = local_var_resp.text().await?;
        let local_var_entity: Option<GetGroupUpcomingBillingInvoiceError> =
            serde_json::from_str(&local_var_content).ok();
        let local_var_error = ResponseContent {
            status: local_var_status,
            content: local_var_content,
            entity: local_var_entity,
            retry_delay: local_var_retry_delay,
        };
        Err(Error::ResponseError(local_var_error))
    }
}

/// Retrieve upcoming invoice for QCS group billing customer.
pub async fn get_group_upcoming_billing_invoice(
    configuration: &configuration::Configuration,
    group_name: &str,
) -> Result<models::BillingUpcomingInvoice, Error<GetGroupUpcomingBillingInvoiceError>> {
    let mut backoff = configuration.backoff.clone();
    let mut refreshed_credentials = false;
    let method = reqwest::Method::GET;
    loop {
        let result = get_group_upcoming_billing_invoice_inner(
            configuration,
            &mut backoff,
            group_name.clone(),
        )
        .await;

        match result {
            Ok(result) => return Ok(result),
            Err(Error::ResponseError(response)) => {
                if !refreshed_credentials
                    && matches!(
                        response.status,
                        StatusCode::FORBIDDEN | StatusCode::UNAUTHORIZED
                    )
                {
                    configuration.qcs_config.refresh().await?;
                    refreshed_credentials = true;
                    continue;
                } else if let Some(duration) = response.retry_delay {
                    tokio::time::sleep(duration).await;
                    continue;
                }

                return Err(Error::ResponseError(response));
            }
            Err(Error::Reqwest(error)) => {
                if let Some(duration) = duration_from_reqwest_error(&method, &error, &mut backoff) {
                    tokio::time::sleep(duration).await;
                    continue;
                }

                return Err(Error::Reqwest(error));
            }
            Err(Error::Io(error)) => {
                if let Some(duration) = duration_from_io_error(&method, &error, &mut backoff) {
                    tokio::time::sleep(duration).await;
                    continue;
                }

                return Err(Error::Io(error));
            }
            Err(error) => return Err(error),
        }
    }
}
async fn get_user_balance_inner(
    configuration: &configuration::Configuration,
    backoff: &mut ExponentialBackoff,
    user_id: &str,
) -> Result<models::AccountBalance, Error<GetUserBalanceError>> {
    let local_var_configuration = configuration;
    // add a prefix to parameters to efficiently prevent name collisions
    let p_path_user_id = user_id;

    let local_var_client = &local_var_configuration.client;

    let local_var_uri_str = format!(
        "{}/v1/users/{userId}/balance",
        local_var_configuration.qcs_config.api_url(),
        userId = crate::apis::urlencode(p_path_user_id)
    );
    let mut local_var_req_builder =
        local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str());

    #[cfg(feature = "tracing")]
    {
        // Ignore parsing errors if the URL is invalid for some reason.
        // If it is invalid, it will turn up as an error later when actually making the request.
        let local_var_do_tracing = local_var_uri_str
            .parse::<::url::Url>()
            .ok()
            .is_none_or(|url| {
                configuration
                    .qcs_config
                    .should_trace(&::urlpattern::UrlPatternMatchInput::Url(url))
            });

        if local_var_do_tracing {
            ::tracing::debug!(
                url=%local_var_uri_str,
                method="GET",
                "making get_user_balance request",
            );
        }
    }

    // Use the QCS Bearer token if a client OAuthSession is present,
    // but do not require one when the security schema says it is optional.
    {
        use qcs_api_client_common::configuration::TokenError;

        #[allow(
            clippy::nonminimal_bool,
            clippy::eq_op,
            reason = "Logic must be done at runtime since it cannot be handled by the mustache template engine."
        )]
        let is_jwt_bearer_optional: bool = false || "JWTBearer" == "JWTBearerOptional";

        let token = local_var_configuration
            .qcs_config
            .get_bearer_access_token()
            .await;

        if is_jwt_bearer_optional && matches!(token, Err(TokenError::NoCredentials)) {
            // the client is configured without any OAuthSession, but this call does not require one.
            #[cfg(feature = "tracing")]
            tracing::debug!(
                "No client credentials found, but this call does not require authentication."
            );
        } else {
            local_var_req_builder = local_var_req_builder.bearer_auth(token?.secret());
        }
    }

    let local_var_req = local_var_req_builder.build()?;
    let local_var_resp = local_var_client.execute(local_var_req).await?;

    let local_var_status = local_var_resp.status();
    let local_var_raw_content_type = local_var_resp
        .headers()
        .get("content-type")
        .and_then(|v| v.to_str().ok())
        .unwrap_or("application/octet-stream")
        .to_string();
    let local_var_content_type = super::ContentType::from(local_var_raw_content_type.as_str());

    if !local_var_status.is_client_error() && !local_var_status.is_server_error() {
        let local_var_content = local_var_resp.text().await?;
        match local_var_content_type {
            ContentType::Json => serde_path_to_error::deserialize(
                &mut serde_json::Deserializer::from_str(&local_var_content),
            )
            .map_err(Error::from),
            ContentType::Text => Err(Error::InvalidContentType {
                content_type: local_var_raw_content_type,
                return_type: "models::AccountBalance",
            }),
            ContentType::Unsupported(unknown_type) => Err(Error::InvalidContentType {
                content_type: unknown_type,
                return_type: "models::AccountBalance",
            }),
        }
    } else {
        let local_var_retry_delay =
            duration_from_response(local_var_resp.status(), local_var_resp.headers(), backoff);
        let local_var_content = local_var_resp.text().await?;
        let local_var_entity: Option<GetUserBalanceError> =
            serde_json::from_str(&local_var_content).ok();
        let local_var_error = ResponseContent {
            status: local_var_status,
            content: local_var_content,
            entity: local_var_entity,
            retry_delay: local_var_retry_delay,
        };
        Err(Error::ResponseError(local_var_error))
    }
}

/// Retrieve the balance of the requested QCS user account.
pub async fn get_user_balance(
    configuration: &configuration::Configuration,
    user_id: &str,
) -> Result<models::AccountBalance, Error<GetUserBalanceError>> {
    let mut backoff = configuration.backoff.clone();
    let mut refreshed_credentials = false;
    let method = reqwest::Method::GET;
    loop {
        let result = get_user_balance_inner(configuration, &mut backoff, user_id.clone()).await;

        match result {
            Ok(result) => return Ok(result),
            Err(Error::ResponseError(response)) => {
                if !refreshed_credentials
                    && matches!(
                        response.status,
                        StatusCode::FORBIDDEN | StatusCode::UNAUTHORIZED
                    )
                {
                    configuration.qcs_config.refresh().await?;
                    refreshed_credentials = true;
                    continue;
                } else if let Some(duration) = response.retry_delay {
                    tokio::time::sleep(duration).await;
                    continue;
                }

                return Err(Error::ResponseError(response));
            }
            Err(Error::Reqwest(error)) => {
                if let Some(duration) = duration_from_reqwest_error(&method, &error, &mut backoff) {
                    tokio::time::sleep(duration).await;
                    continue;
                }

                return Err(Error::Reqwest(error));
            }
            Err(Error::Io(error)) => {
                if let Some(duration) = duration_from_io_error(&method, &error, &mut backoff) {
                    tokio::time::sleep(duration).await;
                    continue;
                }

                return Err(Error::Io(error));
            }
            Err(error) => return Err(error),
        }
    }
}
async fn get_user_billing_customer_inner(
    configuration: &configuration::Configuration,
    backoff: &mut ExponentialBackoff,
    user_id: &str,
) -> Result<models::BillingCustomer, Error<GetUserBillingCustomerError>> {
    let local_var_configuration = configuration;
    // add a prefix to parameters to efficiently prevent name collisions
    let p_path_user_id = user_id;

    let local_var_client = &local_var_configuration.client;

    let local_var_uri_str = format!(
        "{}/v1/users/{userId}/billingCustomer",
        local_var_configuration.qcs_config.api_url(),
        userId = crate::apis::urlencode(p_path_user_id)
    );
    let mut local_var_req_builder =
        local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str());

    #[cfg(feature = "tracing")]
    {
        // Ignore parsing errors if the URL is invalid for some reason.
        // If it is invalid, it will turn up as an error later when actually making the request.
        let local_var_do_tracing = local_var_uri_str
            .parse::<::url::Url>()
            .ok()
            .is_none_or(|url| {
                configuration
                    .qcs_config
                    .should_trace(&::urlpattern::UrlPatternMatchInput::Url(url))
            });

        if local_var_do_tracing {
            ::tracing::debug!(
                url=%local_var_uri_str,
                method="GET",
                "making get_user_billing_customer request",
            );
        }
    }

    // Use the QCS Bearer token if a client OAuthSession is present,
    // but do not require one when the security schema says it is optional.
    {
        use qcs_api_client_common::configuration::TokenError;

        #[allow(
            clippy::nonminimal_bool,
            clippy::eq_op,
            reason = "Logic must be done at runtime since it cannot be handled by the mustache template engine."
        )]
        let is_jwt_bearer_optional: bool = false || "JWTBearer" == "JWTBearerOptional";

        let token = local_var_configuration
            .qcs_config
            .get_bearer_access_token()
            .await;

        if is_jwt_bearer_optional && matches!(token, Err(TokenError::NoCredentials)) {
            // the client is configured without any OAuthSession, but this call does not require one.
            #[cfg(feature = "tracing")]
            tracing::debug!(
                "No client credentials found, but this call does not require authentication."
            );
        } else {
            local_var_req_builder = local_var_req_builder.bearer_auth(token?.secret());
        }
    }

    let local_var_req = local_var_req_builder.build()?;
    let local_var_resp = local_var_client.execute(local_var_req).await?;

    let local_var_status = local_var_resp.status();
    let local_var_raw_content_type = local_var_resp
        .headers()
        .get("content-type")
        .and_then(|v| v.to_str().ok())
        .unwrap_or("application/octet-stream")
        .to_string();
    let local_var_content_type = super::ContentType::from(local_var_raw_content_type.as_str());

    if !local_var_status.is_client_error() && !local_var_status.is_server_error() {
        let local_var_content = local_var_resp.text().await?;
        match local_var_content_type {
            ContentType::Json => serde_path_to_error::deserialize(
                &mut serde_json::Deserializer::from_str(&local_var_content),
            )
            .map_err(Error::from),
            ContentType::Text => Err(Error::InvalidContentType {
                content_type: local_var_raw_content_type,
                return_type: "models::BillingCustomer",
            }),
            ContentType::Unsupported(unknown_type) => Err(Error::InvalidContentType {
                content_type: unknown_type,
                return_type: "models::BillingCustomer",
            }),
        }
    } else {
        let local_var_retry_delay =
            duration_from_response(local_var_resp.status(), local_var_resp.headers(), backoff);
        let local_var_content = local_var_resp.text().await?;
        let local_var_entity: Option<GetUserBillingCustomerError> =
            serde_json::from_str(&local_var_content).ok();
        let local_var_error = ResponseContent {
            status: local_var_status,
            content: local_var_content,
            entity: local_var_entity,
            retry_delay: local_var_retry_delay,
        };
        Err(Error::ResponseError(local_var_error))
    }
}

/// Retrieve billing customer for a QCS user account.
pub async fn get_user_billing_customer(
    configuration: &configuration::Configuration,
    user_id: &str,
) -> Result<models::BillingCustomer, Error<GetUserBillingCustomerError>> {
    let mut backoff = configuration.backoff.clone();
    let mut refreshed_credentials = false;
    let method = reqwest::Method::GET;
    loop {
        let result =
            get_user_billing_customer_inner(configuration, &mut backoff, user_id.clone()).await;

        match result {
            Ok(result) => return Ok(result),
            Err(Error::ResponseError(response)) => {
                if !refreshed_credentials
                    && matches!(
                        response.status,
                        StatusCode::FORBIDDEN | StatusCode::UNAUTHORIZED
                    )
                {
                    configuration.qcs_config.refresh().await?;
                    refreshed_credentials = true;
                    continue;
                } else if let Some(duration) = response.retry_delay {
                    tokio::time::sleep(duration).await;
                    continue;
                }

                return Err(Error::ResponseError(response));
            }
            Err(Error::Reqwest(error)) => {
                if let Some(duration) = duration_from_reqwest_error(&method, &error, &mut backoff) {
                    tokio::time::sleep(duration).await;
                    continue;
                }

                return Err(Error::Reqwest(error));
            }
            Err(Error::Io(error)) => {
                if let Some(duration) = duration_from_io_error(&method, &error, &mut backoff) {
                    tokio::time::sleep(duration).await;
                    continue;
                }

                return Err(Error::Io(error));
            }
            Err(error) => return Err(error),
        }
    }
}
async fn get_user_event_billing_price_inner(
    configuration: &configuration::Configuration,
    backoff: &mut ExponentialBackoff,
    user_id: &str,
    get_account_event_billing_price_request: crate::models::GetAccountEventBillingPriceRequest,
) -> Result<models::EventBillingPriceRate, Error<GetUserEventBillingPriceError>> {
    let local_var_configuration = configuration;
    // add a prefix to parameters to efficiently prevent name collisions
    let p_path_user_id = user_id;
    let p_body_get_account_event_billing_price_request = get_account_event_billing_price_request;

    let local_var_client = &local_var_configuration.client;

    let local_var_uri_str = format!(
        "{}/v1/users/{userId}/eventBillingPrices:get",
        local_var_configuration.qcs_config.api_url(),
        userId = crate::apis::urlencode(p_path_user_id)
    );
    let mut local_var_req_builder =
        local_var_client.request(reqwest::Method::POST, local_var_uri_str.as_str());

    #[cfg(feature = "tracing")]
    {
        // Ignore parsing errors if the URL is invalid for some reason.
        // If it is invalid, it will turn up as an error later when actually making the request.
        let local_var_do_tracing = local_var_uri_str
            .parse::<::url::Url>()
            .ok()
            .is_none_or(|url| {
                configuration
                    .qcs_config
                    .should_trace(&::urlpattern::UrlPatternMatchInput::Url(url))
            });

        if local_var_do_tracing {
            ::tracing::debug!(
                url=%local_var_uri_str,
                method="POST",
                "making get_user_event_billing_price request",
            );
        }
    }

    // Use the QCS Bearer token if a client OAuthSession is present,
    // but do not require one when the security schema says it is optional.
    {
        use qcs_api_client_common::configuration::TokenError;

        #[allow(
            clippy::nonminimal_bool,
            clippy::eq_op,
            reason = "Logic must be done at runtime since it cannot be handled by the mustache template engine."
        )]
        let is_jwt_bearer_optional: bool = false || "JWTBearer" == "JWTBearerOptional";

        let token = local_var_configuration
            .qcs_config
            .get_bearer_access_token()
            .await;

        if is_jwt_bearer_optional && matches!(token, Err(TokenError::NoCredentials)) {
            // the client is configured without any OAuthSession, but this call does not require one.
            #[cfg(feature = "tracing")]
            tracing::debug!(
                "No client credentials found, but this call does not require authentication."
            );
        } else {
            local_var_req_builder = local_var_req_builder.bearer_auth(token?.secret());
        }
    }

    local_var_req_builder =
        local_var_req_builder.json(&p_body_get_account_event_billing_price_request);

    let local_var_req = local_var_req_builder.build()?;
    let local_var_resp = local_var_client.execute(local_var_req).await?;

    let local_var_status = local_var_resp.status();
    let local_var_raw_content_type = local_var_resp
        .headers()
        .get("content-type")
        .and_then(|v| v.to_str().ok())
        .unwrap_or("application/octet-stream")
        .to_string();
    let local_var_content_type = super::ContentType::from(local_var_raw_content_type.as_str());

    if !local_var_status.is_client_error() && !local_var_status.is_server_error() {
        let local_var_content = local_var_resp.text().await?;
        match local_var_content_type {
            ContentType::Json => serde_path_to_error::deserialize(
                &mut serde_json::Deserializer::from_str(&local_var_content),
            )
            .map_err(Error::from),
            ContentType::Text => Err(Error::InvalidContentType {
                content_type: local_var_raw_content_type,
                return_type: "models::EventBillingPriceRate",
            }),
            ContentType::Unsupported(unknown_type) => Err(Error::InvalidContentType {
                content_type: unknown_type,
                return_type: "models::EventBillingPriceRate",
            }),
        }
    } else {
        let local_var_retry_delay =
            duration_from_response(local_var_resp.status(), local_var_resp.headers(), backoff);
        let local_var_content = local_var_resp.text().await?;
        let local_var_entity: Option<GetUserEventBillingPriceError> =
            serde_json::from_str(&local_var_content).ok();
        let local_var_error = ResponseContent {
            status: local_var_status,
            content: local_var_content,
            entity: local_var_entity,
            retry_delay: local_var_retry_delay,
        };
        Err(Error::ResponseError(local_var_error))
    }
}

/// Retrieve `EventBillingPrice` for a user for a specific event. If no price is configured this operation will return a default `EventBillingPrice` for the specified `product`.
pub async fn get_user_event_billing_price(
    configuration: &configuration::Configuration,
    user_id: &str,
    get_account_event_billing_price_request: crate::models::GetAccountEventBillingPriceRequest,
) -> Result<models::EventBillingPriceRate, Error<GetUserEventBillingPriceError>> {
    let mut backoff = configuration.backoff.clone();
    let mut refreshed_credentials = false;
    let method = reqwest::Method::POST;
    loop {
        let result = get_user_event_billing_price_inner(
            configuration,
            &mut backoff,
            user_id.clone(),
            get_account_event_billing_price_request.clone(),
        )
        .await;

        match result {
            Ok(result) => return Ok(result),
            Err(Error::ResponseError(response)) => {
                if !refreshed_credentials
                    && matches!(
                        response.status,
                        StatusCode::FORBIDDEN | StatusCode::UNAUTHORIZED
                    )
                {
                    configuration.qcs_config.refresh().await?;
                    refreshed_credentials = true;
                    continue;
                } else if let Some(duration) = response.retry_delay {
                    tokio::time::sleep(duration).await;
                    continue;
                }

                return Err(Error::ResponseError(response));
            }
            Err(Error::Reqwest(error)) => {
                if let Some(duration) = duration_from_reqwest_error(&method, &error, &mut backoff) {
                    tokio::time::sleep(duration).await;
                    continue;
                }

                return Err(Error::Reqwest(error));
            }
            Err(Error::Io(error)) => {
                if let Some(duration) = duration_from_io_error(&method, &error, &mut backoff) {
                    tokio::time::sleep(duration).await;
                    continue;
                }

                return Err(Error::Io(error));
            }
            Err(error) => return Err(error),
        }
    }
}
async fn get_user_upcoming_billing_invoice_inner(
    configuration: &configuration::Configuration,
    backoff: &mut ExponentialBackoff,
    user_id: &str,
) -> Result<models::BillingUpcomingInvoice, Error<GetUserUpcomingBillingInvoiceError>> {
    let local_var_configuration = configuration;
    // add a prefix to parameters to efficiently prevent name collisions
    let p_path_user_id = user_id;

    let local_var_client = &local_var_configuration.client;

    let local_var_uri_str = format!(
        "{}/v1/users/{userId}/billingInvoices:getUpcoming",
        local_var_configuration.qcs_config.api_url(),
        userId = crate::apis::urlencode(p_path_user_id)
    );
    let mut local_var_req_builder =
        local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str());

    #[cfg(feature = "tracing")]
    {
        // Ignore parsing errors if the URL is invalid for some reason.
        // If it is invalid, it will turn up as an error later when actually making the request.
        let local_var_do_tracing = local_var_uri_str
            .parse::<::url::Url>()
            .ok()
            .is_none_or(|url| {
                configuration
                    .qcs_config
                    .should_trace(&::urlpattern::UrlPatternMatchInput::Url(url))
            });

        if local_var_do_tracing {
            ::tracing::debug!(
                url=%local_var_uri_str,
                method="GET",
                "making get_user_upcoming_billing_invoice request",
            );
        }
    }

    // Use the QCS Bearer token if a client OAuthSession is present,
    // but do not require one when the security schema says it is optional.
    {
        use qcs_api_client_common::configuration::TokenError;

        #[allow(
            clippy::nonminimal_bool,
            clippy::eq_op,
            reason = "Logic must be done at runtime since it cannot be handled by the mustache template engine."
        )]
        let is_jwt_bearer_optional: bool = false || "JWTBearer" == "JWTBearerOptional";

        let token = local_var_configuration
            .qcs_config
            .get_bearer_access_token()
            .await;

        if is_jwt_bearer_optional && matches!(token, Err(TokenError::NoCredentials)) {
            // the client is configured without any OAuthSession, but this call does not require one.
            #[cfg(feature = "tracing")]
            tracing::debug!(
                "No client credentials found, but this call does not require authentication."
            );
        } else {
            local_var_req_builder = local_var_req_builder.bearer_auth(token?.secret());
        }
    }

    let local_var_req = local_var_req_builder.build()?;
    let local_var_resp = local_var_client.execute(local_var_req).await?;

    let local_var_status = local_var_resp.status();
    let local_var_raw_content_type = local_var_resp
        .headers()
        .get("content-type")
        .and_then(|v| v.to_str().ok())
        .unwrap_or("application/octet-stream")
        .to_string();
    let local_var_content_type = super::ContentType::from(local_var_raw_content_type.as_str());

    if !local_var_status.is_client_error() && !local_var_status.is_server_error() {
        let local_var_content = local_var_resp.text().await?;
        match local_var_content_type {
            ContentType::Json => serde_path_to_error::deserialize(
                &mut serde_json::Deserializer::from_str(&local_var_content),
            )
            .map_err(Error::from),
            ContentType::Text => Err(Error::InvalidContentType {
                content_type: local_var_raw_content_type,
                return_type: "models::BillingUpcomingInvoice",
            }),
            ContentType::Unsupported(unknown_type) => Err(Error::InvalidContentType {
                content_type: unknown_type,
                return_type: "models::BillingUpcomingInvoice",
            }),
        }
    } else {
        let local_var_retry_delay =
            duration_from_response(local_var_resp.status(), local_var_resp.headers(), backoff);
        let local_var_content = local_var_resp.text().await?;
        let local_var_entity: Option<GetUserUpcomingBillingInvoiceError> =
            serde_json::from_str(&local_var_content).ok();
        let local_var_error = ResponseContent {
            status: local_var_status,
            content: local_var_content,
            entity: local_var_entity,
            retry_delay: local_var_retry_delay,
        };
        Err(Error::ResponseError(local_var_error))
    }
}

/// Retrieve upcoming invoice for QCS user billing customer.
pub async fn get_user_upcoming_billing_invoice(
    configuration: &configuration::Configuration,
    user_id: &str,
) -> Result<models::BillingUpcomingInvoice, Error<GetUserUpcomingBillingInvoiceError>> {
    let mut backoff = configuration.backoff.clone();
    let mut refreshed_credentials = false;
    let method = reqwest::Method::GET;
    loop {
        let result =
            get_user_upcoming_billing_invoice_inner(configuration, &mut backoff, user_id.clone())
                .await;

        match result {
            Ok(result) => return Ok(result),
            Err(Error::ResponseError(response)) => {
                if !refreshed_credentials
                    && matches!(
                        response.status,
                        StatusCode::FORBIDDEN | StatusCode::UNAUTHORIZED
                    )
                {
                    configuration.qcs_config.refresh().await?;
                    refreshed_credentials = true;
                    continue;
                } else if let Some(duration) = response.retry_delay {
                    tokio::time::sleep(duration).await;
                    continue;
                }

                return Err(Error::ResponseError(response));
            }
            Err(Error::Reqwest(error)) => {
                if let Some(duration) = duration_from_reqwest_error(&method, &error, &mut backoff) {
                    tokio::time::sleep(duration).await;
                    continue;
                }

                return Err(Error::Reqwest(error));
            }
            Err(Error::Io(error)) => {
                if let Some(duration) = duration_from_io_error(&method, &error, &mut backoff) {
                    tokio::time::sleep(duration).await;
                    continue;
                }

                return Err(Error::Io(error));
            }
            Err(error) => return Err(error),
        }
    }
}
async fn get_viewer_user_onboarding_completed_inner(
    configuration: &configuration::Configuration,
    backoff: &mut ExponentialBackoff,
) -> Result<models::ViewerUserOnboardingCompleted, Error<GetViewerUserOnboardingCompletedError>> {
    let local_var_configuration = configuration;

    let local_var_client = &local_var_configuration.client;

    let local_var_uri_str = format!(
        "{}/v1/viewer/onboardingCompleted",
        local_var_configuration.qcs_config.api_url()
    );
    let mut local_var_req_builder =
        local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str());

    #[cfg(feature = "tracing")]
    {
        // Ignore parsing errors if the URL is invalid for some reason.
        // If it is invalid, it will turn up as an error later when actually making the request.
        let local_var_do_tracing = local_var_uri_str
            .parse::<::url::Url>()
            .ok()
            .is_none_or(|url| {
                configuration
                    .qcs_config
                    .should_trace(&::urlpattern::UrlPatternMatchInput::Url(url))
            });

        if local_var_do_tracing {
            ::tracing::debug!(
                url=%local_var_uri_str,
                method="GET",
                "making get_viewer_user_onboarding_completed request",
            );
        }
    }

    // Use the QCS Bearer token if a client OAuthSession is present,
    // but do not require one when the security schema says it is optional.
    {
        use qcs_api_client_common::configuration::TokenError;

        #[allow(
            clippy::nonminimal_bool,
            clippy::eq_op,
            reason = "Logic must be done at runtime since it cannot be handled by the mustache template engine."
        )]
        let is_jwt_bearer_optional: bool = false || "JWTBearer" == "JWTBearerOptional";

        let token = local_var_configuration
            .qcs_config
            .get_bearer_access_token()
            .await;

        if is_jwt_bearer_optional && matches!(token, Err(TokenError::NoCredentials)) {
            // the client is configured without any OAuthSession, but this call does not require one.
            #[cfg(feature = "tracing")]
            tracing::debug!(
                "No client credentials found, but this call does not require authentication."
            );
        } else {
            local_var_req_builder = local_var_req_builder.bearer_auth(token?.secret());
        }
    }

    let local_var_req = local_var_req_builder.build()?;
    let local_var_resp = local_var_client.execute(local_var_req).await?;

    let local_var_status = local_var_resp.status();
    let local_var_raw_content_type = local_var_resp
        .headers()
        .get("content-type")
        .and_then(|v| v.to_str().ok())
        .unwrap_or("application/octet-stream")
        .to_string();
    let local_var_content_type = super::ContentType::from(local_var_raw_content_type.as_str());

    if !local_var_status.is_client_error() && !local_var_status.is_server_error() {
        let local_var_content = local_var_resp.text().await?;
        match local_var_content_type {
            ContentType::Json => serde_path_to_error::deserialize(
                &mut serde_json::Deserializer::from_str(&local_var_content),
            )
            .map_err(Error::from),
            ContentType::Text => Err(Error::InvalidContentType {
                content_type: local_var_raw_content_type,
                return_type: "models::ViewerUserOnboardingCompleted",
            }),
            ContentType::Unsupported(unknown_type) => Err(Error::InvalidContentType {
                content_type: unknown_type,
                return_type: "models::ViewerUserOnboardingCompleted",
            }),
        }
    } else {
        let local_var_retry_delay =
            duration_from_response(local_var_resp.status(), local_var_resp.headers(), backoff);
        let local_var_content = local_var_resp.text().await?;
        let local_var_entity: Option<GetViewerUserOnboardingCompletedError> =
            serde_json::from_str(&local_var_content).ok();
        let local_var_error = ResponseContent {
            status: local_var_status,
            content: local_var_content,
            entity: local_var_entity,
            retry_delay: local_var_retry_delay,
        };
        Err(Error::ResponseError(local_var_error))
    }
}

/// Get the onboarding status of the authenticated user.
pub async fn get_viewer_user_onboarding_completed(
    configuration: &configuration::Configuration,
) -> Result<models::ViewerUserOnboardingCompleted, Error<GetViewerUserOnboardingCompletedError>> {
    let mut backoff = configuration.backoff.clone();
    let mut refreshed_credentials = false;
    let method = reqwest::Method::GET;
    loop {
        let result = get_viewer_user_onboarding_completed_inner(configuration, &mut backoff).await;

        match result {
            Ok(result) => return Ok(result),
            Err(Error::ResponseError(response)) => {
                if !refreshed_credentials
                    && matches!(
                        response.status,
                        StatusCode::FORBIDDEN | StatusCode::UNAUTHORIZED
                    )
                {
                    configuration.qcs_config.refresh().await?;
                    refreshed_credentials = true;
                    continue;
                } else if let Some(duration) = response.retry_delay {
                    tokio::time::sleep(duration).await;
                    continue;
                }

                return Err(Error::ResponseError(response));
            }
            Err(Error::Reqwest(error)) => {
                if let Some(duration) = duration_from_reqwest_error(&method, &error, &mut backoff) {
                    tokio::time::sleep(duration).await;
                    continue;
                }

                return Err(Error::Reqwest(error));
            }
            Err(Error::Io(error)) => {
                if let Some(duration) = duration_from_io_error(&method, &error, &mut backoff) {
                    tokio::time::sleep(duration).await;
                    continue;
                }

                return Err(Error::Io(error));
            }
            Err(error) => return Err(error),
        }
    }
}
async fn list_group_billing_invoice_lines_inner(
    configuration: &configuration::Configuration,
    backoff: &mut ExponentialBackoff,
    group_name: &str,
    billing_invoice_id: &str,
    page_token: Option<&str>,
    page_size: Option<i64>,
) -> Result<models::ListAccountBillingInvoiceLinesResponse, Error<ListGroupBillingInvoiceLinesError>>
{
    let local_var_configuration = configuration;
    // add a prefix to parameters to efficiently prevent name collisions
    let p_path_group_name = group_name;
    let p_path_billing_invoice_id = billing_invoice_id;
    let p_query_page_token = page_token;
    let p_query_page_size = page_size;

    let local_var_client = &local_var_configuration.client;

    let local_var_uri_str = format!(
        "{}/v1/groups/{groupName}/billingInvoices/{billingInvoiceId}/lines",
        local_var_configuration.qcs_config.api_url(),
        groupName = crate::apis::urlencode(p_path_group_name),
        billingInvoiceId = crate::apis::urlencode(p_path_billing_invoice_id)
    );
    let mut local_var_req_builder =
        local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str());

    #[cfg(feature = "tracing")]
    {
        // Ignore parsing errors if the URL is invalid for some reason.
        // If it is invalid, it will turn up as an error later when actually making the request.
        let local_var_do_tracing = local_var_uri_str
            .parse::<::url::Url>()
            .ok()
            .is_none_or(|url| {
                configuration
                    .qcs_config
                    .should_trace(&::urlpattern::UrlPatternMatchInput::Url(url))
            });

        if local_var_do_tracing {
            ::tracing::debug!(
                url=%local_var_uri_str,
                method="GET",
                "making list_group_billing_invoice_lines request",
            );
        }
    }

    if let Some(ref local_var_str) = p_query_page_token {
        local_var_req_builder =
            local_var_req_builder.query(&[("pageToken", &local_var_str.to_string())]);
    }
    if let Some(ref local_var_str) = p_query_page_size {
        local_var_req_builder =
            local_var_req_builder.query(&[("pageSize", &local_var_str.to_string())]);
    }

    // Use the QCS Bearer token if a client OAuthSession is present,
    // but do not require one when the security schema says it is optional.
    {
        use qcs_api_client_common::configuration::TokenError;

        #[allow(
            clippy::nonminimal_bool,
            clippy::eq_op,
            reason = "Logic must be done at runtime since it cannot be handled by the mustache template engine."
        )]
        let is_jwt_bearer_optional: bool = false || "JWTBearer" == "JWTBearerOptional";

        let token = local_var_configuration
            .qcs_config
            .get_bearer_access_token()
            .await;

        if is_jwt_bearer_optional && matches!(token, Err(TokenError::NoCredentials)) {
            // the client is configured without any OAuthSession, but this call does not require one.
            #[cfg(feature = "tracing")]
            tracing::debug!(
                "No client credentials found, but this call does not require authentication."
            );
        } else {
            local_var_req_builder = local_var_req_builder.bearer_auth(token?.secret());
        }
    }

    let local_var_req = local_var_req_builder.build()?;
    let local_var_resp = local_var_client.execute(local_var_req).await?;

    let local_var_status = local_var_resp.status();
    let local_var_raw_content_type = local_var_resp
        .headers()
        .get("content-type")
        .and_then(|v| v.to_str().ok())
        .unwrap_or("application/octet-stream")
        .to_string();
    let local_var_content_type = super::ContentType::from(local_var_raw_content_type.as_str());

    if !local_var_status.is_client_error() && !local_var_status.is_server_error() {
        let local_var_content = local_var_resp.text().await?;
        match local_var_content_type {
            ContentType::Json => serde_path_to_error::deserialize(
                &mut serde_json::Deserializer::from_str(&local_var_content),
            )
            .map_err(Error::from),
            ContentType::Text => Err(Error::InvalidContentType {
                content_type: local_var_raw_content_type,
                return_type: "models::ListAccountBillingInvoiceLinesResponse",
            }),
            ContentType::Unsupported(unknown_type) => Err(Error::InvalidContentType {
                content_type: unknown_type,
                return_type: "models::ListAccountBillingInvoiceLinesResponse",
            }),
        }
    } else {
        let local_var_retry_delay =
            duration_from_response(local_var_resp.status(), local_var_resp.headers(), backoff);
        let local_var_content = local_var_resp.text().await?;
        let local_var_entity: Option<ListGroupBillingInvoiceLinesError> =
            serde_json::from_str(&local_var_content).ok();
        let local_var_error = ResponseContent {
            status: local_var_status,
            content: local_var_content,
            entity: local_var_entity,
            retry_delay: local_var_retry_delay,
        };
        Err(Error::ResponseError(local_var_error))
    }
}

/// Retrieve billing invoice lines for a QCS group account's invoice.
pub async fn list_group_billing_invoice_lines(
    configuration: &configuration::Configuration,
    group_name: &str,
    billing_invoice_id: &str,
    page_token: Option<&str>,
    page_size: Option<i64>,
) -> Result<models::ListAccountBillingInvoiceLinesResponse, Error<ListGroupBillingInvoiceLinesError>>
{
    let mut backoff = configuration.backoff.clone();
    let mut refreshed_credentials = false;
    let method = reqwest::Method::GET;
    loop {
        let result = list_group_billing_invoice_lines_inner(
            configuration,
            &mut backoff,
            group_name.clone(),
            billing_invoice_id.clone(),
            page_token.clone(),
            page_size.clone(),
        )
        .await;

        match result {
            Ok(result) => return Ok(result),
            Err(Error::ResponseError(response)) => {
                if !refreshed_credentials
                    && matches!(
                        response.status,
                        StatusCode::FORBIDDEN | StatusCode::UNAUTHORIZED
                    )
                {
                    configuration.qcs_config.refresh().await?;
                    refreshed_credentials = true;
                    continue;
                } else if let Some(duration) = response.retry_delay {
                    tokio::time::sleep(duration).await;
                    continue;
                }

                return Err(Error::ResponseError(response));
            }
            Err(Error::Reqwest(error)) => {
                if let Some(duration) = duration_from_reqwest_error(&method, &error, &mut backoff) {
                    tokio::time::sleep(duration).await;
                    continue;
                }

                return Err(Error::Reqwest(error));
            }
            Err(Error::Io(error)) => {
                if let Some(duration) = duration_from_io_error(&method, &error, &mut backoff) {
                    tokio::time::sleep(duration).await;
                    continue;
                }

                return Err(Error::Io(error));
            }
            Err(error) => return Err(error),
        }
    }
}
async fn list_group_billing_invoices_inner(
    configuration: &configuration::Configuration,
    backoff: &mut ExponentialBackoff,
    group_name: &str,
    page_token: Option<&str>,
    page_size: Option<i64>,
) -> Result<models::ListAccountBillingInvoicesResponse, Error<ListGroupBillingInvoicesError>> {
    let local_var_configuration = configuration;
    // add a prefix to parameters to efficiently prevent name collisions
    let p_path_group_name = group_name;
    let p_query_page_token = page_token;
    let p_query_page_size = page_size;

    let local_var_client = &local_var_configuration.client;

    let local_var_uri_str = format!(
        "{}/v1/groups/{groupName}/billingInvoices",
        local_var_configuration.qcs_config.api_url(),
        groupName = crate::apis::urlencode(p_path_group_name)
    );
    let mut local_var_req_builder =
        local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str());

    #[cfg(feature = "tracing")]
    {
        // Ignore parsing errors if the URL is invalid for some reason.
        // If it is invalid, it will turn up as an error later when actually making the request.
        let local_var_do_tracing = local_var_uri_str
            .parse::<::url::Url>()
            .ok()
            .is_none_or(|url| {
                configuration
                    .qcs_config
                    .should_trace(&::urlpattern::UrlPatternMatchInput::Url(url))
            });

        if local_var_do_tracing {
            ::tracing::debug!(
                url=%local_var_uri_str,
                method="GET",
                "making list_group_billing_invoices request",
            );
        }
    }

    if let Some(ref local_var_str) = p_query_page_token {
        local_var_req_builder =
            local_var_req_builder.query(&[("pageToken", &local_var_str.to_string())]);
    }
    if let Some(ref local_var_str) = p_query_page_size {
        local_var_req_builder =
            local_var_req_builder.query(&[("pageSize", &local_var_str.to_string())]);
    }

    // Use the QCS Bearer token if a client OAuthSession is present,
    // but do not require one when the security schema says it is optional.
    {
        use qcs_api_client_common::configuration::TokenError;

        #[allow(
            clippy::nonminimal_bool,
            clippy::eq_op,
            reason = "Logic must be done at runtime since it cannot be handled by the mustache template engine."
        )]
        let is_jwt_bearer_optional: bool = false || "JWTBearer" == "JWTBearerOptional";

        let token = local_var_configuration
            .qcs_config
            .get_bearer_access_token()
            .await;

        if is_jwt_bearer_optional && matches!(token, Err(TokenError::NoCredentials)) {
            // the client is configured without any OAuthSession, but this call does not require one.
            #[cfg(feature = "tracing")]
            tracing::debug!(
                "No client credentials found, but this call does not require authentication."
            );
        } else {
            local_var_req_builder = local_var_req_builder.bearer_auth(token?.secret());
        }
    }

    let local_var_req = local_var_req_builder.build()?;
    let local_var_resp = local_var_client.execute(local_var_req).await?;

    let local_var_status = local_var_resp.status();
    let local_var_raw_content_type = local_var_resp
        .headers()
        .get("content-type")
        .and_then(|v| v.to_str().ok())
        .unwrap_or("application/octet-stream")
        .to_string();
    let local_var_content_type = super::ContentType::from(local_var_raw_content_type.as_str());

    if !local_var_status.is_client_error() && !local_var_status.is_server_error() {
        let local_var_content = local_var_resp.text().await?;
        match local_var_content_type {
            ContentType::Json => serde_path_to_error::deserialize(
                &mut serde_json::Deserializer::from_str(&local_var_content),
            )
            .map_err(Error::from),
            ContentType::Text => Err(Error::InvalidContentType {
                content_type: local_var_raw_content_type,
                return_type: "models::ListAccountBillingInvoicesResponse",
            }),
            ContentType::Unsupported(unknown_type) => Err(Error::InvalidContentType {
                content_type: unknown_type,
                return_type: "models::ListAccountBillingInvoicesResponse",
            }),
        }
    } else {
        let local_var_retry_delay =
            duration_from_response(local_var_resp.status(), local_var_resp.headers(), backoff);
        let local_var_content = local_var_resp.text().await?;
        let local_var_entity: Option<ListGroupBillingInvoicesError> =
            serde_json::from_str(&local_var_content).ok();
        let local_var_error = ResponseContent {
            status: local_var_status,
            content: local_var_content,
            entity: local_var_entity,
            retry_delay: local_var_retry_delay,
        };
        Err(Error::ResponseError(local_var_error))
    }
}

/// Retrieve billing invoices for a QCS group account.
pub async fn list_group_billing_invoices(
    configuration: &configuration::Configuration,
    group_name: &str,
    page_token: Option<&str>,
    page_size: Option<i64>,
) -> Result<models::ListAccountBillingInvoicesResponse, Error<ListGroupBillingInvoicesError>> {
    let mut backoff = configuration.backoff.clone();
    let mut refreshed_credentials = false;
    let method = reqwest::Method::GET;
    loop {
        let result = list_group_billing_invoices_inner(
            configuration,
            &mut backoff,
            group_name.clone(),
            page_token.clone(),
            page_size.clone(),
        )
        .await;

        match result {
            Ok(result) => return Ok(result),
            Err(Error::ResponseError(response)) => {
                if !refreshed_credentials
                    && matches!(
                        response.status,
                        StatusCode::FORBIDDEN | StatusCode::UNAUTHORIZED
                    )
                {
                    configuration.qcs_config.refresh().await?;
                    refreshed_credentials = true;
                    continue;
                } else if let Some(duration) = response.retry_delay {
                    tokio::time::sleep(duration).await;
                    continue;
                }

                return Err(Error::ResponseError(response));
            }
            Err(Error::Reqwest(error)) => {
                if let Some(duration) = duration_from_reqwest_error(&method, &error, &mut backoff) {
                    tokio::time::sleep(duration).await;
                    continue;
                }

                return Err(Error::Reqwest(error));
            }
            Err(Error::Io(error)) => {
                if let Some(duration) = duration_from_io_error(&method, &error, &mut backoff) {
                    tokio::time::sleep(duration).await;
                    continue;
                }

                return Err(Error::Io(error));
            }
            Err(error) => return Err(error),
        }
    }
}
async fn list_group_upcoming_billing_invoice_lines_inner(
    configuration: &configuration::Configuration,
    backoff: &mut ExponentialBackoff,
    group_name: &str,
    page_token: Option<&str>,
    page_size: Option<i64>,
) -> Result<
    models::ListAccountBillingInvoiceLinesResponse,
    Error<ListGroupUpcomingBillingInvoiceLinesError>,
> {
    let local_var_configuration = configuration;
    // add a prefix to parameters to efficiently prevent name collisions
    let p_path_group_name = group_name;
    let p_query_page_token = page_token;
    let p_query_page_size = page_size;

    let local_var_client = &local_var_configuration.client;

    let local_var_uri_str = format!(
        "{}/v1/groups/{groupName}/billingInvoices:listUpcomingLines",
        local_var_configuration.qcs_config.api_url(),
        groupName = crate::apis::urlencode(p_path_group_name)
    );
    let mut local_var_req_builder =
        local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str());

    #[cfg(feature = "tracing")]
    {
        // Ignore parsing errors if the URL is invalid for some reason.
        // If it is invalid, it will turn up as an error later when actually making the request.
        let local_var_do_tracing = local_var_uri_str
            .parse::<::url::Url>()
            .ok()
            .is_none_or(|url| {
                configuration
                    .qcs_config
                    .should_trace(&::urlpattern::UrlPatternMatchInput::Url(url))
            });

        if local_var_do_tracing {
            ::tracing::debug!(
                url=%local_var_uri_str,
                method="GET",
                "making list_group_upcoming_billing_invoice_lines request",
            );
        }
    }

    if let Some(ref local_var_str) = p_query_page_token {
        local_var_req_builder =
            local_var_req_builder.query(&[("pageToken", &local_var_str.to_string())]);
    }
    if let Some(ref local_var_str) = p_query_page_size {
        local_var_req_builder =
            local_var_req_builder.query(&[("pageSize", &local_var_str.to_string())]);
    }

    // Use the QCS Bearer token if a client OAuthSession is present,
    // but do not require one when the security schema says it is optional.
    {
        use qcs_api_client_common::configuration::TokenError;

        #[allow(
            clippy::nonminimal_bool,
            clippy::eq_op,
            reason = "Logic must be done at runtime since it cannot be handled by the mustache template engine."
        )]
        let is_jwt_bearer_optional: bool = false || "JWTBearer" == "JWTBearerOptional";

        let token = local_var_configuration
            .qcs_config
            .get_bearer_access_token()
            .await;

        if is_jwt_bearer_optional && matches!(token, Err(TokenError::NoCredentials)) {
            // the client is configured without any OAuthSession, but this call does not require one.
            #[cfg(feature = "tracing")]
            tracing::debug!(
                "No client credentials found, but this call does not require authentication."
            );
        } else {
            local_var_req_builder = local_var_req_builder.bearer_auth(token?.secret());
        }
    }

    let local_var_req = local_var_req_builder.build()?;
    let local_var_resp = local_var_client.execute(local_var_req).await?;

    let local_var_status = local_var_resp.status();
    let local_var_raw_content_type = local_var_resp
        .headers()
        .get("content-type")
        .and_then(|v| v.to_str().ok())
        .unwrap_or("application/octet-stream")
        .to_string();
    let local_var_content_type = super::ContentType::from(local_var_raw_content_type.as_str());

    if !local_var_status.is_client_error() && !local_var_status.is_server_error() {
        let local_var_content = local_var_resp.text().await?;
        match local_var_content_type {
            ContentType::Json => serde_path_to_error::deserialize(
                &mut serde_json::Deserializer::from_str(&local_var_content),
            )
            .map_err(Error::from),
            ContentType::Text => Err(Error::InvalidContentType {
                content_type: local_var_raw_content_type,
                return_type: "models::ListAccountBillingInvoiceLinesResponse",
            }),
            ContentType::Unsupported(unknown_type) => Err(Error::InvalidContentType {
                content_type: unknown_type,
                return_type: "models::ListAccountBillingInvoiceLinesResponse",
            }),
        }
    } else {
        let local_var_retry_delay =
            duration_from_response(local_var_resp.status(), local_var_resp.headers(), backoff);
        let local_var_content = local_var_resp.text().await?;
        let local_var_entity: Option<ListGroupUpcomingBillingInvoiceLinesError> =
            serde_json::from_str(&local_var_content).ok();
        let local_var_error = ResponseContent {
            status: local_var_status,
            content: local_var_content,
            entity: local_var_entity,
            retry_delay: local_var_retry_delay,
        };
        Err(Error::ResponseError(local_var_error))
    }
}

/// List invoice lines for QCS group billing customer upcoming invoice.
pub async fn list_group_upcoming_billing_invoice_lines(
    configuration: &configuration::Configuration,
    group_name: &str,
    page_token: Option<&str>,
    page_size: Option<i64>,
) -> Result<
    models::ListAccountBillingInvoiceLinesResponse,
    Error<ListGroupUpcomingBillingInvoiceLinesError>,
> {
    let mut backoff = configuration.backoff.clone();
    let mut refreshed_credentials = false;
    let method = reqwest::Method::GET;
    loop {
        let result = list_group_upcoming_billing_invoice_lines_inner(
            configuration,
            &mut backoff,
            group_name.clone(),
            page_token.clone(),
            page_size.clone(),
        )
        .await;

        match result {
            Ok(result) => return Ok(result),
            Err(Error::ResponseError(response)) => {
                if !refreshed_credentials
                    && matches!(
                        response.status,
                        StatusCode::FORBIDDEN | StatusCode::UNAUTHORIZED
                    )
                {
                    configuration.qcs_config.refresh().await?;
                    refreshed_credentials = true;
                    continue;
                } else if let Some(duration) = response.retry_delay {
                    tokio::time::sleep(duration).await;
                    continue;
                }

                return Err(Error::ResponseError(response));
            }
            Err(Error::Reqwest(error)) => {
                if let Some(duration) = duration_from_reqwest_error(&method, &error, &mut backoff) {
                    tokio::time::sleep(duration).await;
                    continue;
                }

                return Err(Error::Reqwest(error));
            }
            Err(Error::Io(error)) => {
                if let Some(duration) = duration_from_io_error(&method, &error, &mut backoff) {
                    tokio::time::sleep(duration).await;
                    continue;
                }

                return Err(Error::Io(error));
            }
            Err(error) => return Err(error),
        }
    }
}
async fn list_group_users_inner(
    configuration: &configuration::Configuration,
    backoff: &mut ExponentialBackoff,
    group_name: &str,
    page_size: Option<i64>,
    page_token: Option<&str>,
) -> Result<models::ListGroupUsersResponse, Error<ListGroupUsersError>> {
    let local_var_configuration = configuration;
    // add a prefix to parameters to efficiently prevent name collisions
    let p_path_group_name = group_name;
    let p_query_page_size = page_size;
    let p_query_page_token = page_token;

    let local_var_client = &local_var_configuration.client;

    let local_var_uri_str = format!(
        "{}/v1/groups/{groupName}/users",
        local_var_configuration.qcs_config.api_url(),
        groupName = crate::apis::urlencode(p_path_group_name)
    );
    let mut local_var_req_builder =
        local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str());

    #[cfg(feature = "tracing")]
    {
        // Ignore parsing errors if the URL is invalid for some reason.
        // If it is invalid, it will turn up as an error later when actually making the request.
        let local_var_do_tracing = local_var_uri_str
            .parse::<::url::Url>()
            .ok()
            .is_none_or(|url| {
                configuration
                    .qcs_config
                    .should_trace(&::urlpattern::UrlPatternMatchInput::Url(url))
            });

        if local_var_do_tracing {
            ::tracing::debug!(
                url=%local_var_uri_str,
                method="GET",
                "making list_group_users request",
            );
        }
    }

    if let Some(ref local_var_str) = p_query_page_size {
        local_var_req_builder =
            local_var_req_builder.query(&[("pageSize", &local_var_str.to_string())]);
    }
    if let Some(ref local_var_str) = p_query_page_token {
        local_var_req_builder =
            local_var_req_builder.query(&[("pageToken", &local_var_str.to_string())]);
    }

    // Use the QCS Bearer token if a client OAuthSession is present,
    // but do not require one when the security schema says it is optional.
    {
        use qcs_api_client_common::configuration::TokenError;

        #[allow(
            clippy::nonminimal_bool,
            clippy::eq_op,
            reason = "Logic must be done at runtime since it cannot be handled by the mustache template engine."
        )]
        let is_jwt_bearer_optional: bool = false || "JWTBearer" == "JWTBearerOptional";

        let token = local_var_configuration
            .qcs_config
            .get_bearer_access_token()
            .await;

        if is_jwt_bearer_optional && matches!(token, Err(TokenError::NoCredentials)) {
            // the client is configured without any OAuthSession, but this call does not require one.
            #[cfg(feature = "tracing")]
            tracing::debug!(
                "No client credentials found, but this call does not require authentication."
            );
        } else {
            local_var_req_builder = local_var_req_builder.bearer_auth(token?.secret());
        }
    }

    let local_var_req = local_var_req_builder.build()?;
    let local_var_resp = local_var_client.execute(local_var_req).await?;

    let local_var_status = local_var_resp.status();
    let local_var_raw_content_type = local_var_resp
        .headers()
        .get("content-type")
        .and_then(|v| v.to_str().ok())
        .unwrap_or("application/octet-stream")
        .to_string();
    let local_var_content_type = super::ContentType::from(local_var_raw_content_type.as_str());

    if !local_var_status.is_client_error() && !local_var_status.is_server_error() {
        let local_var_content = local_var_resp.text().await?;
        match local_var_content_type {
            ContentType::Json => serde_path_to_error::deserialize(
                &mut serde_json::Deserializer::from_str(&local_var_content),
            )
            .map_err(Error::from),
            ContentType::Text => Err(Error::InvalidContentType {
                content_type: local_var_raw_content_type,
                return_type: "models::ListGroupUsersResponse",
            }),
            ContentType::Unsupported(unknown_type) => Err(Error::InvalidContentType {
                content_type: unknown_type,
                return_type: "models::ListGroupUsersResponse",
            }),
        }
    } else {
        let local_var_retry_delay =
            duration_from_response(local_var_resp.status(), local_var_resp.headers(), backoff);
        let local_var_content = local_var_resp.text().await?;
        let local_var_entity: Option<ListGroupUsersError> =
            serde_json::from_str(&local_var_content).ok();
        let local_var_error = ResponseContent {
            status: local_var_status,
            content: local_var_content,
            entity: local_var_entity,
            retry_delay: local_var_retry_delay,
        };
        Err(Error::ResponseError(local_var_error))
    }
}

/// List users belonging to a group. Note, group membership may take several minutes to update within our identity provider. After adding or removing a user to or from a group, please allow up to 60 minutes for changes to be reflected.
pub async fn list_group_users(
    configuration: &configuration::Configuration,
    group_name: &str,
    page_size: Option<i64>,
    page_token: Option<&str>,
) -> Result<models::ListGroupUsersResponse, Error<ListGroupUsersError>> {
    let mut backoff = configuration.backoff.clone();
    let mut refreshed_credentials = false;
    let method = reqwest::Method::GET;
    loop {
        let result = list_group_users_inner(
            configuration,
            &mut backoff,
            group_name.clone(),
            page_size.clone(),
            page_token.clone(),
        )
        .await;

        match result {
            Ok(result) => return Ok(result),
            Err(Error::ResponseError(response)) => {
                if !refreshed_credentials
                    && matches!(
                        response.status,
                        StatusCode::FORBIDDEN | StatusCode::UNAUTHORIZED
                    )
                {
                    configuration.qcs_config.refresh().await?;
                    refreshed_credentials = true;
                    continue;
                } else if let Some(duration) = response.retry_delay {
                    tokio::time::sleep(duration).await;
                    continue;
                }

                return Err(Error::ResponseError(response));
            }
            Err(Error::Reqwest(error)) => {
                if let Some(duration) = duration_from_reqwest_error(&method, &error, &mut backoff) {
                    tokio::time::sleep(duration).await;
                    continue;
                }

                return Err(Error::Reqwest(error));
            }
            Err(Error::Io(error)) => {
                if let Some(duration) = duration_from_io_error(&method, &error, &mut backoff) {
                    tokio::time::sleep(duration).await;
                    continue;
                }

                return Err(Error::Io(error));
            }
            Err(error) => return Err(error),
        }
    }
}
async fn list_user_billing_invoice_lines_inner(
    configuration: &configuration::Configuration,
    backoff: &mut ExponentialBackoff,
    user_id: &str,
    billing_invoice_id: &str,
    page_token: Option<&str>,
    page_size: Option<i64>,
) -> Result<models::ListAccountBillingInvoiceLinesResponse, Error<ListUserBillingInvoiceLinesError>>
{
    let local_var_configuration = configuration;
    // add a prefix to parameters to efficiently prevent name collisions
    let p_path_user_id = user_id;
    let p_path_billing_invoice_id = billing_invoice_id;
    let p_query_page_token = page_token;
    let p_query_page_size = page_size;

    let local_var_client = &local_var_configuration.client;

    let local_var_uri_str = format!(
        "{}/v1/users/{userId}/billingInvoices/{billingInvoiceId}/lines",
        local_var_configuration.qcs_config.api_url(),
        userId = crate::apis::urlencode(p_path_user_id),
        billingInvoiceId = crate::apis::urlencode(p_path_billing_invoice_id)
    );
    let mut local_var_req_builder =
        local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str());

    #[cfg(feature = "tracing")]
    {
        // Ignore parsing errors if the URL is invalid for some reason.
        // If it is invalid, it will turn up as an error later when actually making the request.
        let local_var_do_tracing = local_var_uri_str
            .parse::<::url::Url>()
            .ok()
            .is_none_or(|url| {
                configuration
                    .qcs_config
                    .should_trace(&::urlpattern::UrlPatternMatchInput::Url(url))
            });

        if local_var_do_tracing {
            ::tracing::debug!(
                url=%local_var_uri_str,
                method="GET",
                "making list_user_billing_invoice_lines request",
            );
        }
    }

    if let Some(ref local_var_str) = p_query_page_token {
        local_var_req_builder =
            local_var_req_builder.query(&[("pageToken", &local_var_str.to_string())]);
    }
    if let Some(ref local_var_str) = p_query_page_size {
        local_var_req_builder =
            local_var_req_builder.query(&[("pageSize", &local_var_str.to_string())]);
    }

    // Use the QCS Bearer token if a client OAuthSession is present,
    // but do not require one when the security schema says it is optional.
    {
        use qcs_api_client_common::configuration::TokenError;

        #[allow(
            clippy::nonminimal_bool,
            clippy::eq_op,
            reason = "Logic must be done at runtime since it cannot be handled by the mustache template engine."
        )]
        let is_jwt_bearer_optional: bool = false || "JWTBearer" == "JWTBearerOptional";

        let token = local_var_configuration
            .qcs_config
            .get_bearer_access_token()
            .await;

        if is_jwt_bearer_optional && matches!(token, Err(TokenError::NoCredentials)) {
            // the client is configured without any OAuthSession, but this call does not require one.
            #[cfg(feature = "tracing")]
            tracing::debug!(
                "No client credentials found, but this call does not require authentication."
            );
        } else {
            local_var_req_builder = local_var_req_builder.bearer_auth(token?.secret());
        }
    }

    let local_var_req = local_var_req_builder.build()?;
    let local_var_resp = local_var_client.execute(local_var_req).await?;

    let local_var_status = local_var_resp.status();
    let local_var_raw_content_type = local_var_resp
        .headers()
        .get("content-type")
        .and_then(|v| v.to_str().ok())
        .unwrap_or("application/octet-stream")
        .to_string();
    let local_var_content_type = super::ContentType::from(local_var_raw_content_type.as_str());

    if !local_var_status.is_client_error() && !local_var_status.is_server_error() {
        let local_var_content = local_var_resp.text().await?;
        match local_var_content_type {
            ContentType::Json => serde_path_to_error::deserialize(
                &mut serde_json::Deserializer::from_str(&local_var_content),
            )
            .map_err(Error::from),
            ContentType::Text => Err(Error::InvalidContentType {
                content_type: local_var_raw_content_type,
                return_type: "models::ListAccountBillingInvoiceLinesResponse",
            }),
            ContentType::Unsupported(unknown_type) => Err(Error::InvalidContentType {
                content_type: unknown_type,
                return_type: "models::ListAccountBillingInvoiceLinesResponse",
            }),
        }
    } else {
        let local_var_retry_delay =
            duration_from_response(local_var_resp.status(), local_var_resp.headers(), backoff);
        let local_var_content = local_var_resp.text().await?;
        let local_var_entity: Option<ListUserBillingInvoiceLinesError> =
            serde_json::from_str(&local_var_content).ok();
        let local_var_error = ResponseContent {
            status: local_var_status,
            content: local_var_content,
            entity: local_var_entity,
            retry_delay: local_var_retry_delay,
        };
        Err(Error::ResponseError(local_var_error))
    }
}

/// Retrieve billing invoice lines for a QCS user account's invoice.
pub async fn list_user_billing_invoice_lines(
    configuration: &configuration::Configuration,
    user_id: &str,
    billing_invoice_id: &str,
    page_token: Option<&str>,
    page_size: Option<i64>,
) -> Result<models::ListAccountBillingInvoiceLinesResponse, Error<ListUserBillingInvoiceLinesError>>
{
    let mut backoff = configuration.backoff.clone();
    let mut refreshed_credentials = false;
    let method = reqwest::Method::GET;
    loop {
        let result = list_user_billing_invoice_lines_inner(
            configuration,
            &mut backoff,
            user_id.clone(),
            billing_invoice_id.clone(),
            page_token.clone(),
            page_size.clone(),
        )
        .await;

        match result {
            Ok(result) => return Ok(result),
            Err(Error::ResponseError(response)) => {
                if !refreshed_credentials
                    && matches!(
                        response.status,
                        StatusCode::FORBIDDEN | StatusCode::UNAUTHORIZED
                    )
                {
                    configuration.qcs_config.refresh().await?;
                    refreshed_credentials = true;
                    continue;
                } else if let Some(duration) = response.retry_delay {
                    tokio::time::sleep(duration).await;
                    continue;
                }

                return Err(Error::ResponseError(response));
            }
            Err(Error::Reqwest(error)) => {
                if let Some(duration) = duration_from_reqwest_error(&method, &error, &mut backoff) {
                    tokio::time::sleep(duration).await;
                    continue;
                }

                return Err(Error::Reqwest(error));
            }
            Err(Error::Io(error)) => {
                if let Some(duration) = duration_from_io_error(&method, &error, &mut backoff) {
                    tokio::time::sleep(duration).await;
                    continue;
                }

                return Err(Error::Io(error));
            }
            Err(error) => return Err(error),
        }
    }
}
async fn list_user_billing_invoices_inner(
    configuration: &configuration::Configuration,
    backoff: &mut ExponentialBackoff,
    user_id: &str,
    page_token: Option<&str>,
    page_size: Option<i64>,
) -> Result<models::ListAccountBillingInvoicesResponse, Error<ListUserBillingInvoicesError>> {
    let local_var_configuration = configuration;
    // add a prefix to parameters to efficiently prevent name collisions
    let p_path_user_id = user_id;
    let p_query_page_token = page_token;
    let p_query_page_size = page_size;

    let local_var_client = &local_var_configuration.client;

    let local_var_uri_str = format!(
        "{}/v1/users/{userId}/billingInvoices",
        local_var_configuration.qcs_config.api_url(),
        userId = crate::apis::urlencode(p_path_user_id)
    );
    let mut local_var_req_builder =
        local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str());

    #[cfg(feature = "tracing")]
    {
        // Ignore parsing errors if the URL is invalid for some reason.
        // If it is invalid, it will turn up as an error later when actually making the request.
        let local_var_do_tracing = local_var_uri_str
            .parse::<::url::Url>()
            .ok()
            .is_none_or(|url| {
                configuration
                    .qcs_config
                    .should_trace(&::urlpattern::UrlPatternMatchInput::Url(url))
            });

        if local_var_do_tracing {
            ::tracing::debug!(
                url=%local_var_uri_str,
                method="GET",
                "making list_user_billing_invoices request",
            );
        }
    }

    if let Some(ref local_var_str) = p_query_page_token {
        local_var_req_builder =
            local_var_req_builder.query(&[("pageToken", &local_var_str.to_string())]);
    }
    if let Some(ref local_var_str) = p_query_page_size {
        local_var_req_builder =
            local_var_req_builder.query(&[("pageSize", &local_var_str.to_string())]);
    }

    // Use the QCS Bearer token if a client OAuthSession is present,
    // but do not require one when the security schema says it is optional.
    {
        use qcs_api_client_common::configuration::TokenError;

        #[allow(
            clippy::nonminimal_bool,
            clippy::eq_op,
            reason = "Logic must be done at runtime since it cannot be handled by the mustache template engine."
        )]
        let is_jwt_bearer_optional: bool = false || "JWTBearer" == "JWTBearerOptional";

        let token = local_var_configuration
            .qcs_config
            .get_bearer_access_token()
            .await;

        if is_jwt_bearer_optional && matches!(token, Err(TokenError::NoCredentials)) {
            // the client is configured without any OAuthSession, but this call does not require one.
            #[cfg(feature = "tracing")]
            tracing::debug!(
                "No client credentials found, but this call does not require authentication."
            );
        } else {
            local_var_req_builder = local_var_req_builder.bearer_auth(token?.secret());
        }
    }

    let local_var_req = local_var_req_builder.build()?;
    let local_var_resp = local_var_client.execute(local_var_req).await?;

    let local_var_status = local_var_resp.status();
    let local_var_raw_content_type = local_var_resp
        .headers()
        .get("content-type")
        .and_then(|v| v.to_str().ok())
        .unwrap_or("application/octet-stream")
        .to_string();
    let local_var_content_type = super::ContentType::from(local_var_raw_content_type.as_str());

    if !local_var_status.is_client_error() && !local_var_status.is_server_error() {
        let local_var_content = local_var_resp.text().await?;
        match local_var_content_type {
            ContentType::Json => serde_path_to_error::deserialize(
                &mut serde_json::Deserializer::from_str(&local_var_content),
            )
            .map_err(Error::from),
            ContentType::Text => Err(Error::InvalidContentType {
                content_type: local_var_raw_content_type,
                return_type: "models::ListAccountBillingInvoicesResponse",
            }),
            ContentType::Unsupported(unknown_type) => Err(Error::InvalidContentType {
                content_type: unknown_type,
                return_type: "models::ListAccountBillingInvoicesResponse",
            }),
        }
    } else {
        let local_var_retry_delay =
            duration_from_response(local_var_resp.status(), local_var_resp.headers(), backoff);
        let local_var_content = local_var_resp.text().await?;
        let local_var_entity: Option<ListUserBillingInvoicesError> =
            serde_json::from_str(&local_var_content).ok();
        let local_var_error = ResponseContent {
            status: local_var_status,
            content: local_var_content,
            entity: local_var_entity,
            retry_delay: local_var_retry_delay,
        };
        Err(Error::ResponseError(local_var_error))
    }
}

/// Retrieve billing invoices for a QCS user account.
pub async fn list_user_billing_invoices(
    configuration: &configuration::Configuration,
    user_id: &str,
    page_token: Option<&str>,
    page_size: Option<i64>,
) -> Result<models::ListAccountBillingInvoicesResponse, Error<ListUserBillingInvoicesError>> {
    let mut backoff = configuration.backoff.clone();
    let mut refreshed_credentials = false;
    let method = reqwest::Method::GET;
    loop {
        let result = list_user_billing_invoices_inner(
            configuration,
            &mut backoff,
            user_id.clone(),
            page_token.clone(),
            page_size.clone(),
        )
        .await;

        match result {
            Ok(result) => return Ok(result),
            Err(Error::ResponseError(response)) => {
                if !refreshed_credentials
                    && matches!(
                        response.status,
                        StatusCode::FORBIDDEN | StatusCode::UNAUTHORIZED
                    )
                {
                    configuration.qcs_config.refresh().await?;
                    refreshed_credentials = true;
                    continue;
                } else if let Some(duration) = response.retry_delay {
                    tokio::time::sleep(duration).await;
                    continue;
                }

                return Err(Error::ResponseError(response));
            }
            Err(Error::Reqwest(error)) => {
                if let Some(duration) = duration_from_reqwest_error(&method, &error, &mut backoff) {
                    tokio::time::sleep(duration).await;
                    continue;
                }

                return Err(Error::Reqwest(error));
            }
            Err(Error::Io(error)) => {
                if let Some(duration) = duration_from_io_error(&method, &error, &mut backoff) {
                    tokio::time::sleep(duration).await;
                    continue;
                }

                return Err(Error::Io(error));
            }
            Err(error) => return Err(error),
        }
    }
}
async fn list_user_groups_inner(
    configuration: &configuration::Configuration,
    backoff: &mut ExponentialBackoff,
    user_id: &str,
    page_size: Option<i64>,
    page_token: Option<&str>,
) -> Result<models::ListGroupsResponse, Error<ListUserGroupsError>> {
    let local_var_configuration = configuration;
    // add a prefix to parameters to efficiently prevent name collisions
    let p_path_user_id = user_id;
    let p_query_page_size = page_size;
    let p_query_page_token = page_token;

    let local_var_client = &local_var_configuration.client;

    let local_var_uri_str = format!(
        "{}/v1/users/{userId}/groups",
        local_var_configuration.qcs_config.api_url(),
        userId = crate::apis::urlencode(p_path_user_id)
    );
    let mut local_var_req_builder =
        local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str());

    #[cfg(feature = "tracing")]
    {
        // Ignore parsing errors if the URL is invalid for some reason.
        // If it is invalid, it will turn up as an error later when actually making the request.
        let local_var_do_tracing = local_var_uri_str
            .parse::<::url::Url>()
            .ok()
            .is_none_or(|url| {
                configuration
                    .qcs_config
                    .should_trace(&::urlpattern::UrlPatternMatchInput::Url(url))
            });

        if local_var_do_tracing {
            ::tracing::debug!(
                url=%local_var_uri_str,
                method="GET",
                "making list_user_groups request",
            );
        }
    }

    if let Some(ref local_var_str) = p_query_page_size {
        local_var_req_builder =
            local_var_req_builder.query(&[("pageSize", &local_var_str.to_string())]);
    }
    if let Some(ref local_var_str) = p_query_page_token {
        local_var_req_builder =
            local_var_req_builder.query(&[("pageToken", &local_var_str.to_string())]);
    }

    // Use the QCS Bearer token if a client OAuthSession is present,
    // but do not require one when the security schema says it is optional.
    {
        use qcs_api_client_common::configuration::TokenError;

        #[allow(
            clippy::nonminimal_bool,
            clippy::eq_op,
            reason = "Logic must be done at runtime since it cannot be handled by the mustache template engine."
        )]
        let is_jwt_bearer_optional: bool = false || "JWTBearer" == "JWTBearerOptional";

        let token = local_var_configuration
            .qcs_config
            .get_bearer_access_token()
            .await;

        if is_jwt_bearer_optional && matches!(token, Err(TokenError::NoCredentials)) {
            // the client is configured without any OAuthSession, but this call does not require one.
            #[cfg(feature = "tracing")]
            tracing::debug!(
                "No client credentials found, but this call does not require authentication."
            );
        } else {
            local_var_req_builder = local_var_req_builder.bearer_auth(token?.secret());
        }
    }

    let local_var_req = local_var_req_builder.build()?;
    let local_var_resp = local_var_client.execute(local_var_req).await?;

    let local_var_status = local_var_resp.status();
    let local_var_raw_content_type = local_var_resp
        .headers()
        .get("content-type")
        .and_then(|v| v.to_str().ok())
        .unwrap_or("application/octet-stream")
        .to_string();
    let local_var_content_type = super::ContentType::from(local_var_raw_content_type.as_str());

    if !local_var_status.is_client_error() && !local_var_status.is_server_error() {
        let local_var_content = local_var_resp.text().await?;
        match local_var_content_type {
            ContentType::Json => serde_path_to_error::deserialize(
                &mut serde_json::Deserializer::from_str(&local_var_content),
            )
            .map_err(Error::from),
            ContentType::Text => Err(Error::InvalidContentType {
                content_type: local_var_raw_content_type,
                return_type: "models::ListGroupsResponse",
            }),
            ContentType::Unsupported(unknown_type) => Err(Error::InvalidContentType {
                content_type: unknown_type,
                return_type: "models::ListGroupsResponse",
            }),
        }
    } else {
        let local_var_retry_delay =
            duration_from_response(local_var_resp.status(), local_var_resp.headers(), backoff);
        let local_var_content = local_var_resp.text().await?;
        let local_var_entity: Option<ListUserGroupsError> =
            serde_json::from_str(&local_var_content).ok();
        let local_var_error = ResponseContent {
            status: local_var_status,
            content: local_var_content,
            entity: local_var_entity,
            retry_delay: local_var_retry_delay,
        };
        Err(Error::ResponseError(local_var_error))
    }
}

/// List QCS groups for the requested user
pub async fn list_user_groups(
    configuration: &configuration::Configuration,
    user_id: &str,
    page_size: Option<i64>,
    page_token: Option<&str>,
) -> Result<models::ListGroupsResponse, Error<ListUserGroupsError>> {
    let mut backoff = configuration.backoff.clone();
    let mut refreshed_credentials = false;
    let method = reqwest::Method::GET;
    loop {
        let result = list_user_groups_inner(
            configuration,
            &mut backoff,
            user_id.clone(),
            page_size.clone(),
            page_token.clone(),
        )
        .await;

        match result {
            Ok(result) => return Ok(result),
            Err(Error::ResponseError(response)) => {
                if !refreshed_credentials
                    && matches!(
                        response.status,
                        StatusCode::FORBIDDEN | StatusCode::UNAUTHORIZED
                    )
                {
                    configuration.qcs_config.refresh().await?;
                    refreshed_credentials = true;
                    continue;
                } else if let Some(duration) = response.retry_delay {
                    tokio::time::sleep(duration).await;
                    continue;
                }

                return Err(Error::ResponseError(response));
            }
            Err(Error::Reqwest(error)) => {
                if let Some(duration) = duration_from_reqwest_error(&method, &error, &mut backoff) {
                    tokio::time::sleep(duration).await;
                    continue;
                }

                return Err(Error::Reqwest(error));
            }
            Err(Error::Io(error)) => {
                if let Some(duration) = duration_from_io_error(&method, &error, &mut backoff) {
                    tokio::time::sleep(duration).await;
                    continue;
                }

                return Err(Error::Io(error));
            }
            Err(error) => return Err(error),
        }
    }
}
async fn list_user_upcoming_billing_invoice_lines_inner(
    configuration: &configuration::Configuration,
    backoff: &mut ExponentialBackoff,
    user_id: &str,
    page_token: Option<&str>,
    page_size: Option<i64>,
) -> Result<
    models::ListAccountBillingInvoiceLinesResponse,
    Error<ListUserUpcomingBillingInvoiceLinesError>,
> {
    let local_var_configuration = configuration;
    // add a prefix to parameters to efficiently prevent name collisions
    let p_path_user_id = user_id;
    let p_query_page_token = page_token;
    let p_query_page_size = page_size;

    let local_var_client = &local_var_configuration.client;

    let local_var_uri_str = format!(
        "{}/v1/users/{userId}/billingInvoices:listUpcomingLines",
        local_var_configuration.qcs_config.api_url(),
        userId = crate::apis::urlencode(p_path_user_id)
    );
    let mut local_var_req_builder =
        local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str());

    #[cfg(feature = "tracing")]
    {
        // Ignore parsing errors if the URL is invalid for some reason.
        // If it is invalid, it will turn up as an error later when actually making the request.
        let local_var_do_tracing = local_var_uri_str
            .parse::<::url::Url>()
            .ok()
            .is_none_or(|url| {
                configuration
                    .qcs_config
                    .should_trace(&::urlpattern::UrlPatternMatchInput::Url(url))
            });

        if local_var_do_tracing {
            ::tracing::debug!(
                url=%local_var_uri_str,
                method="GET",
                "making list_user_upcoming_billing_invoice_lines request",
            );
        }
    }

    if let Some(ref local_var_str) = p_query_page_token {
        local_var_req_builder =
            local_var_req_builder.query(&[("pageToken", &local_var_str.to_string())]);
    }
    if let Some(ref local_var_str) = p_query_page_size {
        local_var_req_builder =
            local_var_req_builder.query(&[("pageSize", &local_var_str.to_string())]);
    }

    // Use the QCS Bearer token if a client OAuthSession is present,
    // but do not require one when the security schema says it is optional.
    {
        use qcs_api_client_common::configuration::TokenError;

        #[allow(
            clippy::nonminimal_bool,
            clippy::eq_op,
            reason = "Logic must be done at runtime since it cannot be handled by the mustache template engine."
        )]
        let is_jwt_bearer_optional: bool = false || "JWTBearer" == "JWTBearerOptional";

        let token = local_var_configuration
            .qcs_config
            .get_bearer_access_token()
            .await;

        if is_jwt_bearer_optional && matches!(token, Err(TokenError::NoCredentials)) {
            // the client is configured without any OAuthSession, but this call does not require one.
            #[cfg(feature = "tracing")]
            tracing::debug!(
                "No client credentials found, but this call does not require authentication."
            );
        } else {
            local_var_req_builder = local_var_req_builder.bearer_auth(token?.secret());
        }
    }

    let local_var_req = local_var_req_builder.build()?;
    let local_var_resp = local_var_client.execute(local_var_req).await?;

    let local_var_status = local_var_resp.status();
    let local_var_raw_content_type = local_var_resp
        .headers()
        .get("content-type")
        .and_then(|v| v.to_str().ok())
        .unwrap_or("application/octet-stream")
        .to_string();
    let local_var_content_type = super::ContentType::from(local_var_raw_content_type.as_str());

    if !local_var_status.is_client_error() && !local_var_status.is_server_error() {
        let local_var_content = local_var_resp.text().await?;
        match local_var_content_type {
            ContentType::Json => serde_path_to_error::deserialize(
                &mut serde_json::Deserializer::from_str(&local_var_content),
            )
            .map_err(Error::from),
            ContentType::Text => Err(Error::InvalidContentType {
                content_type: local_var_raw_content_type,
                return_type: "models::ListAccountBillingInvoiceLinesResponse",
            }),
            ContentType::Unsupported(unknown_type) => Err(Error::InvalidContentType {
                content_type: unknown_type,
                return_type: "models::ListAccountBillingInvoiceLinesResponse",
            }),
        }
    } else {
        let local_var_retry_delay =
            duration_from_response(local_var_resp.status(), local_var_resp.headers(), backoff);
        let local_var_content = local_var_resp.text().await?;
        let local_var_entity: Option<ListUserUpcomingBillingInvoiceLinesError> =
            serde_json::from_str(&local_var_content).ok();
        let local_var_error = ResponseContent {
            status: local_var_status,
            content: local_var_content,
            entity: local_var_entity,
            retry_delay: local_var_retry_delay,
        };
        Err(Error::ResponseError(local_var_error))
    }
}

/// List invoice lines for QCS user billing customer upcoming invoice.
pub async fn list_user_upcoming_billing_invoice_lines(
    configuration: &configuration::Configuration,
    user_id: &str,
    page_token: Option<&str>,
    page_size: Option<i64>,
) -> Result<
    models::ListAccountBillingInvoiceLinesResponse,
    Error<ListUserUpcomingBillingInvoiceLinesError>,
> {
    let mut backoff = configuration.backoff.clone();
    let mut refreshed_credentials = false;
    let method = reqwest::Method::GET;
    loop {
        let result = list_user_upcoming_billing_invoice_lines_inner(
            configuration,
            &mut backoff,
            user_id.clone(),
            page_token.clone(),
            page_size.clone(),
        )
        .await;

        match result {
            Ok(result) => return Ok(result),
            Err(Error::ResponseError(response)) => {
                if !refreshed_credentials
                    && matches!(
                        response.status,
                        StatusCode::FORBIDDEN | StatusCode::UNAUTHORIZED
                    )
                {
                    configuration.qcs_config.refresh().await?;
                    refreshed_credentials = true;
                    continue;
                } else if let Some(duration) = response.retry_delay {
                    tokio::time::sleep(duration).await;
                    continue;
                }

                return Err(Error::ResponseError(response));
            }
            Err(Error::Reqwest(error)) => {
                if let Some(duration) = duration_from_reqwest_error(&method, &error, &mut backoff) {
                    tokio::time::sleep(duration).await;
                    continue;
                }

                return Err(Error::Reqwest(error));
            }
            Err(Error::Io(error)) => {
                if let Some(duration) = duration_from_io_error(&method, &error, &mut backoff) {
                    tokio::time::sleep(duration).await;
                    continue;
                }

                return Err(Error::Io(error));
            }
            Err(error) => return Err(error),
        }
    }
}
async fn list_viewer_announcements_inner(
    configuration: &configuration::Configuration,
    backoff: &mut ExponentialBackoff,
    page_size: Option<i64>,
    page_token: Option<&str>,
    include_dismissed: Option<bool>,
) -> Result<models::AnnouncementsResponse, Error<ListViewerAnnouncementsError>> {
    let local_var_configuration = configuration;
    // add a prefix to parameters to efficiently prevent name collisions
    let p_query_page_size = page_size;
    let p_query_page_token = page_token;
    let p_query_include_dismissed = include_dismissed;

    let local_var_client = &local_var_configuration.client;

    let local_var_uri_str = format!(
        "{}/v1/viewer/announcements",
        local_var_configuration.qcs_config.api_url()
    );
    let mut local_var_req_builder =
        local_var_client.request(reqwest::Method::GET, local_var_uri_str.as_str());

    #[cfg(feature = "tracing")]
    {
        // Ignore parsing errors if the URL is invalid for some reason.
        // If it is invalid, it will turn up as an error later when actually making the request.
        let local_var_do_tracing = local_var_uri_str
            .parse::<::url::Url>()
            .ok()
            .is_none_or(|url| {
                configuration
                    .qcs_config
                    .should_trace(&::urlpattern::UrlPatternMatchInput::Url(url))
            });

        if local_var_do_tracing {
            ::tracing::debug!(
                url=%local_var_uri_str,
                method="GET",
                "making list_viewer_announcements request",
            );
        }
    }

    if let Some(ref local_var_str) = p_query_page_size {
        local_var_req_builder =
            local_var_req_builder.query(&[("pageSize", &local_var_str.to_string())]);
    }
    if let Some(ref local_var_str) = p_query_page_token {
        local_var_req_builder =
            local_var_req_builder.query(&[("pageToken", &local_var_str.to_string())]);
    }
    if let Some(ref local_var_str) = p_query_include_dismissed {
        local_var_req_builder =
            local_var_req_builder.query(&[("includeDismissed", &local_var_str.to_string())]);
    }

    // Use the QCS Bearer token if a client OAuthSession is present,
    // but do not require one when the security schema says it is optional.
    {
        use qcs_api_client_common::configuration::TokenError;

        #[allow(
            clippy::nonminimal_bool,
            clippy::eq_op,
            reason = "Logic must be done at runtime since it cannot be handled by the mustache template engine."
        )]
        let is_jwt_bearer_optional: bool = false || "JWTBearer" == "JWTBearerOptional";

        let token = local_var_configuration
            .qcs_config
            .get_bearer_access_token()
            .await;

        if is_jwt_bearer_optional && matches!(token, Err(TokenError::NoCredentials)) {
            // the client is configured without any OAuthSession, but this call does not require one.
            #[cfg(feature = "tracing")]
            tracing::debug!(
                "No client credentials found, but this call does not require authentication."
            );
        } else {
            local_var_req_builder = local_var_req_builder.bearer_auth(token?.secret());
        }
    }

    let local_var_req = local_var_req_builder.build()?;
    let local_var_resp = local_var_client.execute(local_var_req).await?;

    let local_var_status = local_var_resp.status();
    let local_var_raw_content_type = local_var_resp
        .headers()
        .get("content-type")
        .and_then(|v| v.to_str().ok())
        .unwrap_or("application/octet-stream")
        .to_string();
    let local_var_content_type = super::ContentType::from(local_var_raw_content_type.as_str());

    if !local_var_status.is_client_error() && !local_var_status.is_server_error() {
        let local_var_content = local_var_resp.text().await?;
        match local_var_content_type {
            ContentType::Json => serde_path_to_error::deserialize(
                &mut serde_json::Deserializer::from_str(&local_var_content),
            )
            .map_err(Error::from),
            ContentType::Text => Err(Error::InvalidContentType {
                content_type: local_var_raw_content_type,
                return_type: "models::AnnouncementsResponse",
            }),
            ContentType::Unsupported(unknown_type) => Err(Error::InvalidContentType {
                content_type: unknown_type,
                return_type: "models::AnnouncementsResponse",
            }),
        }
    } else {
        let local_var_retry_delay =
            duration_from_response(local_var_resp.status(), local_var_resp.headers(), backoff);
        let local_var_content = local_var_resp.text().await?;
        let local_var_entity: Option<ListViewerAnnouncementsError> =
            serde_json::from_str(&local_var_content).ok();
        let local_var_error = ResponseContent {
            status: local_var_status,
            content: local_var_content,
            entity: local_var_entity,
            retry_delay: local_var_retry_delay,
        };
        Err(Error::ResponseError(local_var_error))
    }
}

/// List all announcements relevant to the authenticating user. By default, does not include dismissed announcements.
pub async fn list_viewer_announcements(
    configuration: &configuration::Configuration,
    page_size: Option<i64>,
    page_token: Option<&str>,
    include_dismissed: Option<bool>,
) -> Result<models::AnnouncementsResponse, Error<ListViewerAnnouncementsError>> {
    let mut backoff = configuration.backoff.clone();
    let mut refreshed_credentials = false;
    let method = reqwest::Method::GET;
    loop {
        let result = list_viewer_announcements_inner(
            configuration,
            &mut backoff,
            page_size.clone(),
            page_token.clone(),
            include_dismissed.clone(),
        )
        .await;

        match result {
            Ok(result) => return Ok(result),
            Err(Error::ResponseError(response)) => {
                if !refreshed_credentials
                    && matches!(
                        response.status,
                        StatusCode::FORBIDDEN | StatusCode::UNAUTHORIZED
                    )
                {
                    configuration.qcs_config.refresh().await?;
                    refreshed_credentials = true;
                    continue;
                } else if let Some(duration) = response.retry_delay {
                    tokio::time::sleep(duration).await;
                    continue;
                }

                return Err(Error::ResponseError(response));
            }
            Err(Error::Reqwest(error)) => {
                if let Some(duration) = duration_from_reqwest_error(&method, &error, &mut backoff) {
                    tokio::time::sleep(duration).await;
                    continue;
                }

                return Err(Error::Reqwest(error));
            }
            Err(Error::Io(error)) => {
                if let Some(duration) = duration_from_io_error(&method, &error, &mut backoff) {
                    tokio::time::sleep(duration).await;
                    continue;
                }

                return Err(Error::Io(error));
            }
            Err(error) => return Err(error),
        }
    }
}
async fn put_viewer_user_onboarding_completed_inner(
    configuration: &configuration::Configuration,
    backoff: &mut ExponentialBackoff,
    viewer_user_onboarding_completed: Option<crate::models::ViewerUserOnboardingCompleted>,
) -> Result<models::ViewerUserOnboardingCompleted, Error<PutViewerUserOnboardingCompletedError>> {
    let local_var_configuration = configuration;
    // add a prefix to parameters to efficiently prevent name collisions
    let p_body_viewer_user_onboarding_completed = viewer_user_onboarding_completed;

    let local_var_client = &local_var_configuration.client;

    let local_var_uri_str = format!(
        "{}/v1/viewer/onboardingCompleted",
        local_var_configuration.qcs_config.api_url()
    );
    let mut local_var_req_builder =
        local_var_client.request(reqwest::Method::PUT, local_var_uri_str.as_str());

    #[cfg(feature = "tracing")]
    {
        // Ignore parsing errors if the URL is invalid for some reason.
        // If it is invalid, it will turn up as an error later when actually making the request.
        let local_var_do_tracing = local_var_uri_str
            .parse::<::url::Url>()
            .ok()
            .is_none_or(|url| {
                configuration
                    .qcs_config
                    .should_trace(&::urlpattern::UrlPatternMatchInput::Url(url))
            });

        if local_var_do_tracing {
            ::tracing::debug!(
                url=%local_var_uri_str,
                method="PUT",
                "making put_viewer_user_onboarding_completed request",
            );
        }
    }

    // Use the QCS Bearer token if a client OAuthSession is present,
    // but do not require one when the security schema says it is optional.
    {
        use qcs_api_client_common::configuration::TokenError;

        #[allow(
            clippy::nonminimal_bool,
            clippy::eq_op,
            reason = "Logic must be done at runtime since it cannot be handled by the mustache template engine."
        )]
        let is_jwt_bearer_optional: bool = false || "JWTBearer" == "JWTBearerOptional";

        let token = local_var_configuration
            .qcs_config
            .get_bearer_access_token()
            .await;

        if is_jwt_bearer_optional && matches!(token, Err(TokenError::NoCredentials)) {
            // the client is configured without any OAuthSession, but this call does not require one.
            #[cfg(feature = "tracing")]
            tracing::debug!(
                "No client credentials found, but this call does not require authentication."
            );
        } else {
            local_var_req_builder = local_var_req_builder.bearer_auth(token?.secret());
        }
    }

    local_var_req_builder = local_var_req_builder.json(&p_body_viewer_user_onboarding_completed);

    let local_var_req = local_var_req_builder.build()?;
    let local_var_resp = local_var_client.execute(local_var_req).await?;

    let local_var_status = local_var_resp.status();
    let local_var_raw_content_type = local_var_resp
        .headers()
        .get("content-type")
        .and_then(|v| v.to_str().ok())
        .unwrap_or("application/octet-stream")
        .to_string();
    let local_var_content_type = super::ContentType::from(local_var_raw_content_type.as_str());

    if !local_var_status.is_client_error() && !local_var_status.is_server_error() {
        let local_var_content = local_var_resp.text().await?;
        match local_var_content_type {
            ContentType::Json => serde_path_to_error::deserialize(
                &mut serde_json::Deserializer::from_str(&local_var_content),
            )
            .map_err(Error::from),
            ContentType::Text => Err(Error::InvalidContentType {
                content_type: local_var_raw_content_type,
                return_type: "models::ViewerUserOnboardingCompleted",
            }),
            ContentType::Unsupported(unknown_type) => Err(Error::InvalidContentType {
                content_type: unknown_type,
                return_type: "models::ViewerUserOnboardingCompleted",
            }),
        }
    } else {
        let local_var_retry_delay =
            duration_from_response(local_var_resp.status(), local_var_resp.headers(), backoff);
        let local_var_content = local_var_resp.text().await?;
        let local_var_entity: Option<PutViewerUserOnboardingCompletedError> =
            serde_json::from_str(&local_var_content).ok();
        let local_var_error = ResponseContent {
            status: local_var_status,
            content: local_var_content,
            entity: local_var_entity,
            retry_delay: local_var_retry_delay,
        };
        Err(Error::ResponseError(local_var_error))
    }
}

/// Update the onboarding status of the authenticated user.
pub async fn put_viewer_user_onboarding_completed(
    configuration: &configuration::Configuration,
    viewer_user_onboarding_completed: Option<crate::models::ViewerUserOnboardingCompleted>,
) -> Result<models::ViewerUserOnboardingCompleted, Error<PutViewerUserOnboardingCompletedError>> {
    let mut backoff = configuration.backoff.clone();
    let mut refreshed_credentials = false;
    let method = reqwest::Method::PUT;
    loop {
        let result = put_viewer_user_onboarding_completed_inner(
            configuration,
            &mut backoff,
            viewer_user_onboarding_completed.clone(),
        )
        .await;

        match result {
            Ok(result) => return Ok(result),
            Err(Error::ResponseError(response)) => {
                if !refreshed_credentials
                    && matches!(
                        response.status,
                        StatusCode::FORBIDDEN | StatusCode::UNAUTHORIZED
                    )
                {
                    configuration.qcs_config.refresh().await?;
                    refreshed_credentials = true;
                    continue;
                } else if let Some(duration) = response.retry_delay {
                    tokio::time::sleep(duration).await;
                    continue;
                }

                return Err(Error::ResponseError(response));
            }
            Err(Error::Reqwest(error)) => {
                if let Some(duration) = duration_from_reqwest_error(&method, &error, &mut backoff) {
                    tokio::time::sleep(duration).await;
                    continue;
                }

                return Err(Error::Reqwest(error));
            }
            Err(Error::Io(error)) => {
                if let Some(duration) = duration_from_io_error(&method, &error, &mut backoff) {
                    tokio::time::sleep(duration).await;
                    continue;
                }

                return Err(Error::Io(error));
            }
            Err(error) => return Err(error),
        }
    }
}
async fn remove_group_user_inner(
    configuration: &configuration::Configuration,
    backoff: &mut ExponentialBackoff,
    remove_group_user_request: crate::models::RemoveGroupUserRequest,
) -> Result<(), Error<RemoveGroupUserError>> {
    let local_var_configuration = configuration;
    // add a prefix to parameters to efficiently prevent name collisions
    let p_body_remove_group_user_request = remove_group_user_request;

    let local_var_client = &local_var_configuration.client;

    let local_var_uri_str = format!(
        "{}/v1/groups:removeUser",
        local_var_configuration.qcs_config.api_url()
    );
    let mut local_var_req_builder =
        local_var_client.request(reqwest::Method::POST, local_var_uri_str.as_str());

    #[cfg(feature = "tracing")]
    {
        // Ignore parsing errors if the URL is invalid for some reason.
        // If it is invalid, it will turn up as an error later when actually making the request.
        let local_var_do_tracing = local_var_uri_str
            .parse::<::url::Url>()
            .ok()
            .is_none_or(|url| {
                configuration
                    .qcs_config
                    .should_trace(&::urlpattern::UrlPatternMatchInput::Url(url))
            });

        if local_var_do_tracing {
            ::tracing::debug!(
                url=%local_var_uri_str,
                method="POST",
                "making remove_group_user request",
            );
        }
    }

    // Use the QCS Bearer token if a client OAuthSession is present,
    // but do not require one when the security schema says it is optional.
    {
        use qcs_api_client_common::configuration::TokenError;

        #[allow(
            clippy::nonminimal_bool,
            clippy::eq_op,
            reason = "Logic must be done at runtime since it cannot be handled by the mustache template engine."
        )]
        let is_jwt_bearer_optional: bool = false || "JWTBearer" == "JWTBearerOptional";

        let token = local_var_configuration
            .qcs_config
            .get_bearer_access_token()
            .await;

        if is_jwt_bearer_optional && matches!(token, Err(TokenError::NoCredentials)) {
            // the client is configured without any OAuthSession, but this call does not require one.
            #[cfg(feature = "tracing")]
            tracing::debug!(
                "No client credentials found, but this call does not require authentication."
            );
        } else {
            local_var_req_builder = local_var_req_builder.bearer_auth(token?.secret());
        }
    }

    local_var_req_builder = local_var_req_builder.json(&p_body_remove_group_user_request);

    let local_var_req = local_var_req_builder.build()?;
    let local_var_resp = local_var_client.execute(local_var_req).await?;

    let local_var_status = local_var_resp.status();

    if !local_var_status.is_client_error() && !local_var_status.is_server_error() {
        Ok(())
    } else {
        let local_var_retry_delay =
            duration_from_response(local_var_resp.status(), local_var_resp.headers(), backoff);
        let local_var_content = local_var_resp.text().await?;
        let local_var_entity: Option<RemoveGroupUserError> =
            serde_json::from_str(&local_var_content).ok();
        let local_var_error = ResponseContent {
            status: local_var_status,
            content: local_var_content,
            entity: local_var_entity,
            retry_delay: local_var_retry_delay,
        };
        Err(Error::ResponseError(local_var_error))
    }
}

/// Remove a user from a group. Note, group membership may take several minutes to update within our identity provider. After removing a user from a group, please allow up to 60 minutes for changes to be reflected.
pub async fn remove_group_user(
    configuration: &configuration::Configuration,
    remove_group_user_request: crate::models::RemoveGroupUserRequest,
) -> Result<(), Error<RemoveGroupUserError>> {
    let mut backoff = configuration.backoff.clone();
    let mut refreshed_credentials = false;
    let method = reqwest::Method::POST;
    loop {
        let result = remove_group_user_inner(
            configuration,
            &mut backoff,
            remove_group_user_request.clone(),
        )
        .await;

        match result {
            Ok(result) => return Ok(result),
            Err(Error::ResponseError(response)) => {
                if !refreshed_credentials
                    && matches!(
                        response.status,
                        StatusCode::FORBIDDEN | StatusCode::UNAUTHORIZED
                    )
                {
                    configuration.qcs_config.refresh().await?;
                    refreshed_credentials = true;
                    continue;
                } else if let Some(duration) = response.retry_delay {
                    tokio::time::sleep(duration).await;
                    continue;
                }

                return Err(Error::ResponseError(response));
            }
            Err(Error::Reqwest(error)) => {
                if let Some(duration) = duration_from_reqwest_error(&method, &error, &mut backoff) {
                    tokio::time::sleep(duration).await;
                    continue;
                }

                return Err(Error::Reqwest(error));
            }
            Err(Error::Io(error)) => {
                if let Some(duration) = duration_from_io_error(&method, &error, &mut backoff) {
                    tokio::time::sleep(duration).await;
                    continue;
                }

                return Err(Error::Io(error));
            }
            Err(error) => return Err(error),
        }
    }
}
async fn update_viewer_user_profile_inner(
    configuration: &configuration::Configuration,
    backoff: &mut ExponentialBackoff,
    update_viewer_user_profile_request: crate::models::UpdateViewerUserProfileRequest,
) -> Result<models::User, Error<UpdateViewerUserProfileError>> {
    let local_var_configuration = configuration;
    // add a prefix to parameters to efficiently prevent name collisions
    let p_body_update_viewer_user_profile_request = update_viewer_user_profile_request;

    let local_var_client = &local_var_configuration.client;

    let local_var_uri_str = format!(
        "{}/v1/viewer/userProfile",
        local_var_configuration.qcs_config.api_url()
    );
    let mut local_var_req_builder =
        local_var_client.request(reqwest::Method::PUT, local_var_uri_str.as_str());

    #[cfg(feature = "tracing")]
    {
        // Ignore parsing errors if the URL is invalid for some reason.
        // If it is invalid, it will turn up as an error later when actually making the request.
        let local_var_do_tracing = local_var_uri_str
            .parse::<::url::Url>()
            .ok()
            .is_none_or(|url| {
                configuration
                    .qcs_config
                    .should_trace(&::urlpattern::UrlPatternMatchInput::Url(url))
            });

        if local_var_do_tracing {
            ::tracing::debug!(
                url=%local_var_uri_str,
                method="PUT",
                "making update_viewer_user_profile request",
            );
        }
    }

    // Use the QCS Bearer token if a client OAuthSession is present,
    // but do not require one when the security schema says it is optional.
    {
        use qcs_api_client_common::configuration::TokenError;

        #[allow(
            clippy::nonminimal_bool,
            clippy::eq_op,
            reason = "Logic must be done at runtime since it cannot be handled by the mustache template engine."
        )]
        let is_jwt_bearer_optional: bool = false || "JWTBearer" == "JWTBearerOptional";

        let token = local_var_configuration
            .qcs_config
            .get_bearer_access_token()
            .await;

        if is_jwt_bearer_optional && matches!(token, Err(TokenError::NoCredentials)) {
            // the client is configured without any OAuthSession, but this call does not require one.
            #[cfg(feature = "tracing")]
            tracing::debug!(
                "No client credentials found, but this call does not require authentication."
            );
        } else {
            local_var_req_builder = local_var_req_builder.bearer_auth(token?.secret());
        }
    }

    local_var_req_builder = local_var_req_builder.json(&p_body_update_viewer_user_profile_request);

    let local_var_req = local_var_req_builder.build()?;
    let local_var_resp = local_var_client.execute(local_var_req).await?;

    let local_var_status = local_var_resp.status();
    let local_var_raw_content_type = local_var_resp
        .headers()
        .get("content-type")
        .and_then(|v| v.to_str().ok())
        .unwrap_or("application/octet-stream")
        .to_string();
    let local_var_content_type = super::ContentType::from(local_var_raw_content_type.as_str());

    if !local_var_status.is_client_error() && !local_var_status.is_server_error() {
        let local_var_content = local_var_resp.text().await?;
        match local_var_content_type {
            ContentType::Json => serde_path_to_error::deserialize(
                &mut serde_json::Deserializer::from_str(&local_var_content),
            )
            .map_err(Error::from),
            ContentType::Text => Err(Error::InvalidContentType {
                content_type: local_var_raw_content_type,
                return_type: "models::User",
            }),
            ContentType::Unsupported(unknown_type) => Err(Error::InvalidContentType {
                content_type: unknown_type,
                return_type: "models::User",
            }),
        }
    } else {
        let local_var_retry_delay =
            duration_from_response(local_var_resp.status(), local_var_resp.headers(), backoff);
        let local_var_content = local_var_resp.text().await?;
        let local_var_entity: Option<UpdateViewerUserProfileError> =
            serde_json::from_str(&local_var_content).ok();
        let local_var_error = ResponseContent {
            status: local_var_status,
            content: local_var_content,
            entity: local_var_entity,
            retry_delay: local_var_retry_delay,
        };
        Err(Error::ResponseError(local_var_error))
    }
}

/// Update the profile of the authenticated user.
pub async fn update_viewer_user_profile(
    configuration: &configuration::Configuration,
    update_viewer_user_profile_request: crate::models::UpdateViewerUserProfileRequest,
) -> Result<models::User, Error<UpdateViewerUserProfileError>> {
    let mut backoff = configuration.backoff.clone();
    let mut refreshed_credentials = false;
    let method = reqwest::Method::PUT;
    loop {
        let result = update_viewer_user_profile_inner(
            configuration,
            &mut backoff,
            update_viewer_user_profile_request.clone(),
        )
        .await;

        match result {
            Ok(result) => return Ok(result),
            Err(Error::ResponseError(response)) => {
                if !refreshed_credentials
                    && matches!(
                        response.status,
                        StatusCode::FORBIDDEN | StatusCode::UNAUTHORIZED
                    )
                {
                    configuration.qcs_config.refresh().await?;
                    refreshed_credentials = true;
                    continue;
                } else if let Some(duration) = response.retry_delay {
                    tokio::time::sleep(duration).await;
                    continue;
                }

                return Err(Error::ResponseError(response));
            }
            Err(Error::Reqwest(error)) => {
                if let Some(duration) = duration_from_reqwest_error(&method, &error, &mut backoff) {
                    tokio::time::sleep(duration).await;
                    continue;
                }

                return Err(Error::Reqwest(error));
            }
            Err(Error::Io(error)) => {
                if let Some(duration) = duration_from_io_error(&method, &error, &mut backoff) {
                    tokio::time::sleep(duration).await;
                    continue;
                }

                return Err(Error::Io(error));
            }
            Err(error) => return Err(error),
        }
    }
}
