/*
 * Zernio API
 *
 * API reference for Zernio. Authenticate with a Bearer API key. Base URL: https://zernio.com/api
 *
 * The version of the OpenAPI document: 1.0.4
 * Contact: support@zernio.com
 * Generated by: https://openapi-generator.tech
 */

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

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

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

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

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

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

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

/// Bookmark a tweet by ID. Requires the bookmark.write OAuth scope. Rate limit: 50 requests per 15-min window.
pub async fn bookmark_post(
    configuration: &configuration::Configuration,
    bookmark_post_request: models::BookmarkPostRequest,
) -> Result<models::BookmarkPost200Response, Error<BookmarkPostError>> {
    // add a prefix to parameters to efficiently prevent name collisions
    let p_body_bookmark_post_request = bookmark_post_request;

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

    if let Some(ref user_agent) = configuration.user_agent {
        req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone());
    }
    if let Some(ref token) = configuration.bearer_access_token {
        req_builder = req_builder.bearer_auth(token.to_owned());
    };
    req_builder = req_builder.json(&p_body_bookmark_post_request);

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

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

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

/// Follow a user on X/Twitter. Requires the follows.write OAuth scope. For protected accounts, a follow request is sent instead (pending_follow will be true).
pub async fn follow_user(
    configuration: &configuration::Configuration,
    follow_user_request: models::FollowUserRequest,
) -> Result<models::FollowUser200Response, Error<FollowUserError>> {
    // add a prefix to parameters to efficiently prevent name collisions
    let p_body_follow_user_request = follow_user_request;

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

    if let Some(ref user_agent) = configuration.user_agent {
        req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone());
    }
    if let Some(ref token) = configuration.bearer_access_token {
        req_builder = req_builder.bearer_auth(token.to_owned());
    };
    req_builder = req_builder.json(&p_body_follow_user_request);

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

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

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

/// Remove a bookmark from a tweet.
pub async fn remove_bookmark(
    configuration: &configuration::Configuration,
    account_id: &str,
    tweet_id: &str,
) -> Result<models::RemoveBookmark200Response, Error<RemoveBookmarkError>> {
    // add a prefix to parameters to efficiently prevent name collisions
    let p_query_account_id = account_id;
    let p_query_tweet_id = tweet_id;

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

    req_builder = req_builder.query(&[("accountId", &p_query_account_id.to_string())]);
    req_builder = req_builder.query(&[("tweetId", &p_query_tweet_id.to_string())]);
    if let Some(ref user_agent) = configuration.user_agent {
        req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone());
    }
    if let Some(ref token) = configuration.bearer_access_token {
        req_builder = req_builder.bearer_auth(token.to_owned());
    };

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

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

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

/// Retweet (repost) a tweet by ID. Rate limit: 50 requests per 15-min window. Shares the 300/3hr creation limit with tweet creation.
pub async fn retweet_post(
    configuration: &configuration::Configuration,
    retweet_post_request: models::RetweetPostRequest,
) -> Result<models::RetweetPost200Response, Error<RetweetPostError>> {
    // add a prefix to parameters to efficiently prevent name collisions
    let p_body_retweet_post_request = retweet_post_request;

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

    if let Some(ref user_agent) = configuration.user_agent {
        req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone());
    }
    if let Some(ref token) = configuration.bearer_access_token {
        req_builder = req_builder.bearer_auth(token.to_owned());
    };
    req_builder = req_builder.json(&p_body_retweet_post_request);

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

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

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

/// Undo a retweet (un-repost a tweet).
pub async fn undo_retweet(
    configuration: &configuration::Configuration,
    account_id: &str,
    tweet_id: &str,
) -> Result<models::UndoRetweet200Response, Error<UndoRetweetError>> {
    // add a prefix to parameters to efficiently prevent name collisions
    let p_query_account_id = account_id;
    let p_query_tweet_id = tweet_id;

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

    req_builder = req_builder.query(&[("accountId", &p_query_account_id.to_string())]);
    req_builder = req_builder.query(&[("tweetId", &p_query_tweet_id.to_string())]);
    if let Some(ref user_agent) = configuration.user_agent {
        req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone());
    }
    if let Some(ref token) = configuration.bearer_access_token {
        req_builder = req_builder.bearer_auth(token.to_owned());
    };

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

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

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

/// Unfollow a user on X/Twitter.
pub async fn unfollow_user(
    configuration: &configuration::Configuration,
    account_id: &str,
    target_user_id: &str,
) -> Result<models::UnfollowUser200Response, Error<UnfollowUserError>> {
    // add a prefix to parameters to efficiently prevent name collisions
    let p_query_account_id = account_id;
    let p_query_target_user_id = target_user_id;

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

    req_builder = req_builder.query(&[("accountId", &p_query_account_id.to_string())]);
    req_builder = req_builder.query(&[("targetUserId", &p_query_target_user_id.to_string())]);
    if let Some(ref user_agent) = configuration.user_agent {
        req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone());
    }
    if let Some(ref token) = configuration.bearer_access_token {
        req_builder = req_builder.bearer_auth(token.to_owned());
    };

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

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

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