/*
 * Ethereal Exchange API
 *
 * Ethereal HTTP API for real-time trading, order management, and market data access.
 *
 * The version of the OpenAPI document: 0.1.0
 *
 * Generated by: https://openapi-generator.tech
 */

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

/// struct for passing parameters to the method [`referral_controller_activate`]
#[derive(Clone, Debug, Default)]
pub struct ReferralControllerActivateParams {
    pub activate_referral_dto: models::ActivateReferralDto,
}

/// struct for passing parameters to the method [`referral_controller_claim_code`]
#[derive(Clone, Debug, Default)]
pub struct ReferralControllerClaimCodeParams {
    pub claim_referral_code_dto: models::ClaimReferralCodeDto,
}

/// struct for passing parameters to the method [`referral_controller_get_code_usage`]
#[derive(Clone, Debug, Default)]
pub struct ReferralControllerGetCodeUsageParams {
    /// Referral code (3-12 alphanumeric uppercase characters)
    pub code: String,
}

/// struct for passing parameters to the method [`referral_controller_get_summary`]
#[derive(Clone, Debug, Default)]
pub struct ReferralControllerGetSummaryParams {
    /// Must be: EIP712Auth
    pub x_ethereal_auth: String,
    /// Address that signed this message (hex)
    pub x_ethereal_sender: String,
    /// The signature from signTypedData(...) signed by the sender
    pub x_ethereal_signature: String,
    /// Intent of the message (action to be taken)
    pub x_ethereal_intent: String,
    /// Message signedAt current timestamp (seconds since Unix Epoch)
    pub x_ethereal_signed_at: String,
    /// Bytes32 encoded subaccount name (0x prefix, zero padded, set when using linked signer)
    pub subaccount: Option<String>,
}

/// struct for passing parameters to the method [`referral_controller_list_referrals`]
#[derive(Clone, Debug, Default)]
pub struct ReferralControllerListReferralsParams {
    /// Must be: EIP712Auth
    pub x_ethereal_auth: String,
    /// Address that signed this message (hex)
    pub x_ethereal_sender: String,
    /// The signature from signTypedData(...) signed by the sender
    pub x_ethereal_signature: String,
    /// Intent of the message (action to be taken)
    pub x_ethereal_intent: String,
    /// Message signedAt current timestamp (seconds since Unix Epoch)
    pub x_ethereal_signed_at: String,
    /// Direction to paginate through objects
    pub order: Option<String>,
    /// Limit the number of objects to return
    pub limit: Option<i32>,
    /// Pointer to the current object in pagination dataset
    pub cursor: Option<String>,
    /// Bytes32 encoded subaccount name (0x prefix, zero padded, set when using linked signer)
    pub subaccount: Option<String>,
    /// Order by field
    pub order_by: Option<String>,
}

/// struct for typed errors of method [`referral_controller_activate`]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum ReferralControllerActivateError {
    Status400(models::BadRequestDto),
    Status401(models::UnauthorizedDto),
    Status403(models::ForbiddenDto),
    Status404(models::NotFoundDto),
    Status422(models::UnprocessableEntityDto),
    Status429(models::TooManyRequestsDto),
    Status500(),
    UnknownValue(serde_json::Value),
}

/// struct for typed errors of method [`referral_controller_claim_code`]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum ReferralControllerClaimCodeError {
    Status400(models::BadRequestDto),
    Status401(models::UnauthorizedDto),
    Status403(models::ForbiddenDto),
    Status404(models::NotFoundDto),
    Status422(models::UnprocessableEntityDto),
    Status429(models::TooManyRequestsDto),
    Status500(),
    UnknownValue(serde_json::Value),
}

/// struct for typed errors of method [`referral_controller_get_code_usage`]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum ReferralControllerGetCodeUsageError {
    Status400(models::BadRequestDto),
    Status401(models::UnauthorizedDto),
    Status403(models::ForbiddenDto),
    Status404(models::NotFoundDto),
    Status422(models::UnprocessableEntityDto),
    Status429(models::TooManyRequestsDto),
    Status500(),
    UnknownValue(serde_json::Value),
}

/// struct for typed errors of method [`referral_controller_get_summary`]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum ReferralControllerGetSummaryError {
    Status400(models::BadRequestDto),
    Status401(models::UnauthorizedDto),
    Status403(models::ForbiddenDto),
    Status404(models::NotFoundDto),
    Status422(models::UnprocessableEntityDto),
    Status429(models::TooManyRequestsDto),
    Status500(),
    UnknownValue(serde_json::Value),
}

/// struct for typed errors of method [`referral_controller_list_referrals`]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum ReferralControllerListReferralsError {
    Status400(models::BadRequestDto),
    Status401(models::UnauthorizedDto),
    Status403(models::ForbiddenDto),
    Status404(models::NotFoundDto),
    Status422(models::UnprocessableEntityDto),
    Status429(models::TooManyRequestsDto),
    Status500(),
    UnknownValue(serde_json::Value),
}

pub async fn referral_controller_activate(
    configuration: &configuration::Configuration,
    params: ReferralControllerActivateParams,
) -> Result<models::ReferralDto, Error<ReferralControllerActivateError>> {
    let uri_str = format!("{}/v1/referral/activate", configuration.base_path);
    let mut req_builder = configuration
        .client
        .request(reqwest::Method::POST, &uri_str);

    if let Some(ref user_agent) = configuration.user_agent {
        req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone());
    }
    req_builder = req_builder.json(&params.activate_referral_dto);

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

    let status = resp.status();
    let content_type = resp
        .headers()
        .get("content-type")
        .and_then(|v| v.to_str().ok())
        .unwrap_or("application/octet-stream");
    let content_type = super::ContentType::from(content_type);

    if !status.is_client_error() && !status.is_server_error() {
        let content = resp.text().await?;
        match content_type {
            ContentType::Json => serde_json::from_str(&content).map_err(Error::from),
            ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::ReferralDto`"))),
            ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::ReferralDto`")))),
        }
    } else {
        let content = resp.text().await?;
        let entity: Option<ReferralControllerActivateError> = serde_json::from_str(&content).ok();
        Err(Error::ResponseError(ResponseContent {
            status,
            content,
            entity,
        }))
    }
}

pub async fn referral_controller_claim_code(
    configuration: &configuration::Configuration,
    params: ReferralControllerClaimCodeParams,
) -> Result<models::ReferralDto, Error<ReferralControllerClaimCodeError>> {
    let uri_str = format!("{}/v1/referral/claim", configuration.base_path);
    let mut req_builder = configuration
        .client
        .request(reqwest::Method::POST, &uri_str);

    if let Some(ref user_agent) = configuration.user_agent {
        req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone());
    }
    req_builder = req_builder.json(&params.claim_referral_code_dto);

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

    let status = resp.status();
    let content_type = resp
        .headers()
        .get("content-type")
        .and_then(|v| v.to_str().ok())
        .unwrap_or("application/octet-stream");
    let content_type = super::ContentType::from(content_type);

    if !status.is_client_error() && !status.is_server_error() {
        let content = resp.text().await?;
        match content_type {
            ContentType::Json => serde_json::from_str(&content).map_err(Error::from),
            ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::ReferralDto`"))),
            ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::ReferralDto`")))),
        }
    } else {
        let content = resp.text().await?;
        let entity: Option<ReferralControllerClaimCodeError> = serde_json::from_str(&content).ok();
        Err(Error::ResponseError(ResponseContent {
            status,
            content,
            entity,
        }))
    }
}

pub async fn referral_controller_get_code_usage(
    configuration: &configuration::Configuration,
    params: ReferralControllerGetCodeUsageParams,
) -> Result<models::ReferralCodeUsageDto, Error<ReferralControllerGetCodeUsageError>> {
    let uri_str = format!(
        "{}/v1/referral/code/{code}",
        configuration.base_path,
        code = crate::apis::urlencode(params.code)
    );
    let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str);

    if let Some(ref user_agent) = configuration.user_agent {
        req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone());
    }

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

    let status = resp.status();
    let content_type = resp
        .headers()
        .get("content-type")
        .and_then(|v| v.to_str().ok())
        .unwrap_or("application/octet-stream");
    let content_type = super::ContentType::from(content_type);

    if !status.is_client_error() && !status.is_server_error() {
        let content = resp.text().await?;
        match content_type {
            ContentType::Json => serde_json::from_str(&content).map_err(Error::from),
            ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::ReferralCodeUsageDto`"))),
            ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::ReferralCodeUsageDto`")))),
        }
    } else {
        let content = resp.text().await?;
        let entity: Option<ReferralControllerGetCodeUsageError> =
            serde_json::from_str(&content).ok();
        Err(Error::ResponseError(ResponseContent {
            status,
            content,
            entity,
        }))
    }
}

pub async fn referral_controller_get_summary(
    configuration: &configuration::Configuration,
    params: ReferralControllerGetSummaryParams,
) -> Result<models::ReferralDto, Error<ReferralControllerGetSummaryError>> {
    let uri_str = format!("{}/v1/referral/summary", configuration.base_path);
    let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str);

    if let Some(ref param_value) = params.subaccount {
        req_builder = req_builder.query(&[("subaccount", &param_value.to_string())]);
    }
    if let Some(ref user_agent) = configuration.user_agent {
        req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone());
    }
    req_builder = req_builder.header("X-Ethereal-Auth", params.x_ethereal_auth.to_string());
    req_builder = req_builder.header("X-Ethereal-Sender", params.x_ethereal_sender.to_string());
    req_builder = req_builder.header(
        "X-Ethereal-Signature",
        params.x_ethereal_signature.to_string(),
    );
    req_builder = req_builder.header("X-Ethereal-Intent", params.x_ethereal_intent.to_string());
    req_builder = req_builder.header(
        "X-Ethereal-SignedAt",
        params.x_ethereal_signed_at.to_string(),
    );

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

    let status = resp.status();
    let content_type = resp
        .headers()
        .get("content-type")
        .and_then(|v| v.to_str().ok())
        .unwrap_or("application/octet-stream");
    let content_type = super::ContentType::from(content_type);

    if !status.is_client_error() && !status.is_server_error() {
        let content = resp.text().await?;
        match content_type {
            ContentType::Json => serde_json::from_str(&content).map_err(Error::from),
            ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::ReferralDto`"))),
            ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::ReferralDto`")))),
        }
    } else {
        let content = resp.text().await?;
        let entity: Option<ReferralControllerGetSummaryError> = serde_json::from_str(&content).ok();
        Err(Error::ResponseError(ResponseContent {
            status,
            content,
            entity,
        }))
    }
}

pub async fn referral_controller_list_referrals(
    configuration: &configuration::Configuration,
    params: ReferralControllerListReferralsParams,
) -> Result<models::PageOfReferralDtos, Error<ReferralControllerListReferralsError>> {
    let uri_str = format!("{}/v1/referral", configuration.base_path);
    let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str);

    if let Some(ref param_value) = params.order {
        req_builder = req_builder.query(&[("order", &param_value.to_string())]);
    }
    if let Some(ref param_value) = params.limit {
        req_builder = req_builder.query(&[("limit", &param_value.to_string())]);
    }
    if let Some(ref param_value) = params.cursor {
        req_builder = req_builder.query(&[("cursor", &param_value.to_string())]);
    }
    if let Some(ref param_value) = params.subaccount {
        req_builder = req_builder.query(&[("subaccount", &param_value.to_string())]);
    }
    if let Some(ref param_value) = params.order_by {
        req_builder = req_builder.query(&[("orderBy", &param_value.to_string())]);
    }
    if let Some(ref user_agent) = configuration.user_agent {
        req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone());
    }
    req_builder = req_builder.header("X-Ethereal-Auth", params.x_ethereal_auth.to_string());
    req_builder = req_builder.header("X-Ethereal-Sender", params.x_ethereal_sender.to_string());
    req_builder = req_builder.header(
        "X-Ethereal-Signature",
        params.x_ethereal_signature.to_string(),
    );
    req_builder = req_builder.header("X-Ethereal-Intent", params.x_ethereal_intent.to_string());
    req_builder = req_builder.header(
        "X-Ethereal-SignedAt",
        params.x_ethereal_signed_at.to_string(),
    );

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

    let status = resp.status();
    let content_type = resp
        .headers()
        .get("content-type")
        .and_then(|v| v.to_str().ok())
        .unwrap_or("application/octet-stream");
    let content_type = super::ContentType::from(content_type);

    if !status.is_client_error() && !status.is_server_error() {
        let content = resp.text().await?;
        match content_type {
            ContentType::Json => serde_json::from_str(&content).map_err(Error::from),
            ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::PageOfReferralDtos`"))),
            ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::PageOfReferralDtos`")))),
        }
    } else {
        let content = resp.text().await?;
        let entity: Option<ReferralControllerListReferralsError> =
            serde_json::from_str(&content).ok();
        Err(Error::ResponseError(ResponseContent {
            status,
            content,
            entity,
        }))
    }
}
