/*
 * Mithril
 *
 * Mithril Compute API
 *
 * The version of the OpenAPI document: 1.0.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 typed errors of method [`create_volume_v2_volumes_post`]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum CreateVolumeV2VolumesPostError {
    Status422(models::HttpValidationError),
    UnknownValue(serde_json::Value),
}

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

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

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

/// Creates a new storage volume.  Args:     user_info: Authenticated user information.     body: Request body containing volume creation details (size, region, etc).  Returns:     VolumeModel: The created volume model.  Raises:     HTTPException: If user unauthorized or creation fails.
pub async fn create_volume_v2_volumes_post(
    configuration: &configuration::Configuration,
    create_volume_request: models::CreateVolumeRequest,
) -> Result<models::VolumeModel, Error<CreateVolumeV2VolumesPostError>> {
    // add a prefix to parameters to efficiently prevent name collisions
    let p_body_create_volume_request = create_volume_request;

    let uri_str = format!("{}/v2/volumes", 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_create_volume_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 => Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::VolumeModel`"))),
            ContentType::Unsupported(unknown_type) => Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::VolumeModel`")))),
        }
    } else {
        let content = resp.text().await?;
        let entity: Option<CreateVolumeV2VolumesPostError> = serde_json::from_str(&content).ok();
        Err(Error::ResponseError(ResponseContent {
            status,
            content,
            entity,
        }))
    }
}

/// Deletes a storage volume.  Permanently removes a volume. The volume must not be currently in use/attached.  Args:     user_info: Authenticated user information.     volume_fid: Identifier of the volume to delete.  Raises:     HTTPException: If volume not found, user unauthorized, or volume is in use.
pub async fn delete_volume_v2_volumes_volume_fid_delete(
    configuration: &configuration::Configuration,
    volume_fid: &str,
) -> Result<(), Error<DeleteVolumeV2VolumesVolumeFidDeleteError>> {
    // add a prefix to parameters to efficiently prevent name collisions
    let p_path_volume_fid = volume_fid;

    let uri_str = format!(
        "{}/v2/volumes/{volume_fid}",
        configuration.base_path,
        volume_fid = crate::apis::urlencode(p_path_volume_fid)
    );
    let mut req_builder = configuration
        .client
        .request(reqwest::Method::DELETE, &uri_str);

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

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

    let status = resp.status();

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

/// Retrieves all storage volumes for a specific project.  Args:     user_info: Authenticated user information.     project: Identifier of the project to list volumes for.     region: Optional region filter.  Returns:     list[VolumeModel]: A list of volume models belonging to the project.  Raises:     HTTPException: If project is missing or user is not authorized.
pub async fn get_volumes_v2_volumes_get(
    configuration: &configuration::Configuration,
    project: &str,
    region: Option<&str>,
) -> Result<Vec<models::VolumeModel>, Error<GetVolumesV2VolumesGetError>> {
    // add a prefix to parameters to efficiently prevent name collisions
    let p_query_project = project;
    let p_query_region = region;

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

    req_builder = req_builder.query(&[("project", &p_query_project.to_string())]);
    if let Some(ref param_value) = p_query_region {
        req_builder = req_builder.query(&[("region", &param_value.to_string())]);
    }
    if let Some(ref user_agent) = configuration.user_agent {
        req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone());
    }
    if let Some(ref token) = configuration.bearer_access_token {
        req_builder = req_builder.bearer_auth(token.to_owned());
    };

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

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

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

/// Updates a storage volume's mutable properties (e.g., name).  Args:     user_info: Authenticated user information.     volume_fid: Identifier of the volume to update.     body: Request body containing updated fields.  Returns:     VolumeModel: The updated volume model.  Raises:     HTTPException: If volume not found or user unauthorized.
pub async fn update_volume_v2_volumes_volume_fid_patch(
    configuration: &configuration::Configuration,
    volume_fid: &str,
    update_volume_request: models::UpdateVolumeRequest,
) -> Result<models::VolumeModel, Error<UpdateVolumeV2VolumesVolumeFidPatchError>> {
    // add a prefix to parameters to efficiently prevent name collisions
    let p_path_volume_fid = volume_fid;
    let p_body_update_volume_request = update_volume_request;

    let uri_str = format!(
        "{}/v2/volumes/{volume_fid}",
        configuration.base_path,
        volume_fid = crate::apis::urlencode(p_path_volume_fid)
    );
    let mut req_builder = configuration
        .client
        .request(reqwest::Method::PATCH, &uri_str);

    if let Some(ref user_agent) = configuration.user_agent {
        req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone());
    }
    if let Some(ref token) = configuration.bearer_access_token {
        req_builder = req_builder.bearer_auth(token.to_owned());
    };
    req_builder = req_builder.json(&p_body_update_volume_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 => Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::VolumeModel`"))),
            ContentType::Unsupported(unknown_type) => Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::VolumeModel`")))),
        }
    } else {
        let content = resp.text().await?;
        let entity: Option<UpdateVolumeV2VolumesVolumeFidPatchError> =
            serde_json::from_str(&content).ok();
        Err(Error::ResponseError(ResponseContent {
            status,
            content,
            entity,
        }))
    }
}
