// Code generated by TofuPilot SDK Generator. DO NOT EDIT.

use crate::client::TofuPilot;
use crate::error::{Error, Result};
use percent_encoding::{utf8_percent_encode, AsciiSet, NON_ALPHANUMERIC};

/// Percent-encode set matching RFC 3986 unreserved characters.
const URI_COMPONENT: &AsciiSet = &NON_ALPHANUMERIC
    .remove(b'-')
    .remove(b'.')
    .remove(b'_')
    .remove(b'~');
use crate::types::*;

/// Client for the Parts API.
#[derive(Debug, Clone)]
pub struct PartsClient<'a> {
    pub(crate) client: &'a TofuPilot,
}

impl<'a> PartsClient<'a> {
    pub(crate) fn new(client: &'a TofuPilot) -> Self {
        Self { client }
    }

    /// List and filter parts
    ///
    /// Retrieve a paginated list of parts and components in your organization. Filter and search by part name, number, or revision number for inventory management.
    pub fn list(&self) -> ListBuilder<'a> {
        ListBuilder::new(self.client)
    }

    /// Create part
    ///
    /// Create a new part. Optionally create with a revision. Part numbers are matched case-insensitively (e.g., "PART-001" and "part-001" are considered the same).
    pub fn create(&self) -> CreateBuilder<'a> {
        CreateBuilder::new(self.client)
    }

    /// Get part
    ///
    /// Retrieve a single part by its number, including all revisions, metadata, and linked units. Part numbers are matched case-insensitively.
    pub fn get(&self) -> GetBuilder<'a> {
        GetBuilder::new(self.client)
    }

    /// Delete part
    ///
    /// Permanently delete a part and all its revisions. This removes all associated data and cannot be undone.
    pub fn delete(&self) -> DeleteBuilder<'a> {
        DeleteBuilder::new(self.client)
    }

    /// Update part
    ///
    /// Update a part's number or name. Identifies the part by its current number in the URL with case-insensitive matching.
    pub fn update(&self) -> UpdateBuilder<'a> {
        UpdateBuilder::new(self.client)
    }

}

// ---------------------------------------------------------------------------
// ListBuilder
// ---------------------------------------------------------------------------

/// Builder for [`PartsClient::list`].
///
/// # Example
///
/// ```no_run
/// use tofupilot::TofuPilot;
///
/// # #[tokio::main]
/// # async fn main() -> tofupilot::Result<()> {
/// let client = TofuPilot::new("your-api-key");
/// let response = client.parts().list()
///     .send()
///     .await?;
/// # Ok(())
/// # }
/// ```
#[derive(Debug)]
pub struct ListBuilder<'a> {
    client: &'a TofuPilot,
    limit: Option<i64>,
    cursor: Option<i64>,
    search_query: Option<String>,
    procedure_ids: Option<Vec<String>>,
    sort_by: Option<PartListSortBy>,
    sort_order: Option<ListSortOrder>,
    server_url: Option<String>,
    timeout: Option<std::time::Duration>,
}

impl<'a> ListBuilder<'a> {
    pub(crate) fn new(client: &'a TofuPilot) -> Self {
        Self {
            client,
            limit: None,
            cursor: None,
            search_query: None,
            procedure_ids: None,
            sort_by: None,
            sort_order: None,
            server_url: None,
            timeout: None,
        }
    }

    /// Set the `limit` query parameter.
    ///
    /// Maximum number of parts to return in a single page.
    pub fn limit(mut self, value: impl Into<i64>) -> Self {
        self.limit = Some(value.into());
        self
    }

    /// Set the `cursor` query parameter.
    pub fn cursor(mut self, value: impl Into<i64>) -> Self {
        self.cursor = Some(value.into());
        self
    }

    /// Set the `search_query` query parameter.
    pub fn search_query(mut self, value: impl Into<String>) -> Self {
        self.search_query = Some(value.into());
        self
    }

    /// Set the `procedure_ids` query parameter.
    pub fn procedure_ids(mut self, value: impl Into<Vec<String>>) -> Self {
        self.procedure_ids = Some(value.into());
        self
    }

    /// Set the `sort_by` query parameter.
    ///
    /// Field to sort results by.
    pub fn sort_by(mut self, value: impl Into<PartListSortBy>) -> Self {
        self.sort_by = Some(value.into());
        self
    }

    /// Set the `sort_order` query parameter.
    ///
    /// Sort order direction.
    pub fn sort_order(mut self, value: impl Into<ListSortOrder>) -> Self {
        self.sort_order = Some(value.into());
        self
    }

    /// Override the server URL for this request.
    pub fn server_url(mut self, url: impl Into<String>) -> Self {
        self.server_url = Some(url.into());
        self
    }

    /// Override the timeout for this request.
    pub fn timeout(mut self, timeout: std::time::Duration) -> Self {
        self.timeout = Some(timeout);
        self
    }

    /// Send the request.
    pub async fn send(self) -> Result<PartListResponse> {

        let base_url = self.server_url
            .as_deref()
            .unwrap_or(&self.client.config.base_url);

        let url = format!("{}{}", base_url, "/v2/parts");

        let mut request = self.client.http.request(
            reqwest::Method::GET,
            &url,
        );

        if let Some(timeout) = self.timeout {
            request = request.timeout(timeout);
        }

        if let Some(ref val) = self.limit {
            request = request.query(&[("limit", val.to_string())]);
        }
        if let Some(ref val) = self.cursor {
            request = request.query(&[("cursor", val.to_string())]);
        }
        if let Some(ref val) = self.search_query {
            request = request.query(&[("search_query", val.to_string())]);
        }
        if let Some(ref val) = self.procedure_ids {
            for item in val {
                request = request.query(&[("procedure_ids", item.to_string())]);
            }
        }
        if let Some(ref val) = self.sort_by {
            request = request.query(&[("sort_by", val.to_string())]);
        }
        if let Some(ref val) = self.sort_order {
            request = request.query(&[("sort_order", val.to_string())]);
        }


        let response = self.client.execute(
            request,
            "part-list",
            base_url,
        ).await?;
        let result: PartListResponse = response.json().await?;
        Ok(result)
    }
}

// ---------------------------------------------------------------------------
// CreateBuilder
// ---------------------------------------------------------------------------

/// Builder for [`PartsClient::create`].
///
/// # Example
///
/// ```no_run
/// use tofupilot::TofuPilot;
///
/// # #[tokio::main]
/// # async fn main() -> tofupilot::Result<()> {
/// let client = TofuPilot::new("your-api-key");
/// let response = client.parts().create()
///     .number("value")
///     .send()
///     .await?;
/// # Ok(())
/// # }
/// ```
#[derive(Debug)]
pub struct CreateBuilder<'a> {
    client: &'a TofuPilot,
    number: Option<String>,
    name: Option<String>,
    revision_number: Option<String>,
    server_url: Option<String>,
    timeout: Option<std::time::Duration>,
}

impl<'a> CreateBuilder<'a> {
    pub(crate) fn new(client: &'a TofuPilot) -> Self {
        Self {
            client,
            number: None,
            name: None,
            revision_number: None,
            server_url: None,
            timeout: None,
        }
    }

    /// Set the `number` field.
    ///
    /// Unique identifier number for the part.
    pub fn number(mut self, value: impl Into<String>) -> Self {
        self.number = Some(value.into());
        self
    }

    /// Set the `name` field.
    ///
    /// Human-readable name for the part. If not provided, a default name will be used.
    pub fn name(mut self, value: impl Into<String>) -> Self {
        self.name = Some(value.into());
        self
    }

    /// Set the `revision_number` field.
    ///
    /// Revision identifier for the part version. If not provided, default revision identifier will be used.
    pub fn revision_number(mut self, value: impl Into<String>) -> Self {
        self.revision_number = Some(value.into());
        self
    }

    /// Set the full request body (alternative to setting individual fields).
    pub fn body(mut self, body: PartCreateRequest) -> Self {
        self.number = Some(body.number);
        if body.name.is_some() {
            self.name = body.name;
        }
        if body.revision_number.is_some() {
            self.revision_number = body.revision_number;
        }
        self
    }

    /// Override the server URL for this request.
    pub fn server_url(mut self, url: impl Into<String>) -> Self {
        self.server_url = Some(url.into());
        self
    }

    /// Override the timeout for this request.
    pub fn timeout(mut self, timeout: std::time::Duration) -> Self {
        self.timeout = Some(timeout);
        self
    }

    /// Send the request.
    pub async fn send(self) -> Result<PartCreateResponse> {

        let base_url = self.server_url
            .as_deref()
            .unwrap_or(&self.client.config.base_url);

        let url = format!("{}{}", base_url, "/v2/parts");

        let mut request = self.client.http.request(
            reqwest::Method::POST,
            &url,
        );

        if let Some(timeout) = self.timeout {
            request = request.timeout(timeout);
        }


        let body = PartCreateRequest {
            number: self.number
                .ok_or_else(|| Error::Validation(
                    "missing required field: number".to_string(),
                ))?,
            name: self.name,
            revision_number: self.revision_number,
        };
        request = request.json(&body);

        let response = self.client.execute(
            request,
            "part-create",
            base_url,
        ).await?;
        let result: PartCreateResponse = response.json().await?;
        Ok(result)
    }
}

// ---------------------------------------------------------------------------
// GetBuilder
// ---------------------------------------------------------------------------

/// Builder for [`PartsClient::get`].
///
/// # Example
///
/// ```no_run
/// use tofupilot::TofuPilot;
///
/// # #[tokio::main]
/// # async fn main() -> tofupilot::Result<()> {
/// let client = TofuPilot::new("your-api-key");
/// let response = client.parts().get()
///     .number("value")
///     .send()
///     .await?;
/// # Ok(())
/// # }
/// ```
#[derive(Debug)]
pub struct GetBuilder<'a> {
    client: &'a TofuPilot,
    number: Option<String>,
    server_url: Option<String>,
    timeout: Option<std::time::Duration>,
}

impl<'a> GetBuilder<'a> {
    pub(crate) fn new(client: &'a TofuPilot) -> Self {
        Self {
            client,
            number: None,
            server_url: None,
            timeout: None,
        }
    }

    /// Set the `number` path parameter.
    ///
    /// Part number of the part to retrieve.
    pub fn number(mut self, value: impl Into<String>) -> Self {
        self.number = Some(value.into());
        self
    }

    /// Override the server URL for this request.
    pub fn server_url(mut self, url: impl Into<String>) -> Self {
        self.server_url = Some(url.into());
        self
    }

    /// Override the timeout for this request.
    pub fn timeout(mut self, timeout: std::time::Duration) -> Self {
        self.timeout = Some(timeout);
        self
    }

    /// Send the request.
    pub async fn send(self) -> Result<PartGetResponse> {
        let number = self.number
            .ok_or_else(|| Error::Validation(
                "missing required path parameter: number".to_string(),
            ))?;
        let number_encoded = utf8_percent_encode(&number, URI_COMPONENT).to_string();

        let base_url = self.server_url
            .as_deref()
            .unwrap_or(&self.client.config.base_url);

        let url = format!(
            "{}/v2/parts/{number}",
            base_url,
            number = number_encoded,
        );

        let mut request = self.client.http.request(
            reqwest::Method::GET,
            &url,
        );

        if let Some(timeout) = self.timeout {
            request = request.timeout(timeout);
        }



        let response = self.client.execute(
            request,
            "part-get",
            base_url,
        ).await?;
        let result: PartGetResponse = response.json().await?;
        Ok(result)
    }
}

// ---------------------------------------------------------------------------
// DeleteBuilder
// ---------------------------------------------------------------------------

/// Builder for [`PartsClient::delete`].
///
/// # Example
///
/// ```no_run
/// use tofupilot::TofuPilot;
///
/// # #[tokio::main]
/// # async fn main() -> tofupilot::Result<()> {
/// let client = TofuPilot::new("your-api-key");
/// let response = client.parts().delete()
///     .number("value")
///     .send()
///     .await?;
/// # Ok(())
/// # }
/// ```
#[derive(Debug)]
pub struct DeleteBuilder<'a> {
    client: &'a TofuPilot,
    number: Option<String>,
    server_url: Option<String>,
    timeout: Option<std::time::Duration>,
}

impl<'a> DeleteBuilder<'a> {
    pub(crate) fn new(client: &'a TofuPilot) -> Self {
        Self {
            client,
            number: None,
            server_url: None,
            timeout: None,
        }
    }

    /// Set the `number` path parameter.
    ///
    /// Part number to delete.
    pub fn number(mut self, value: impl Into<String>) -> Self {
        self.number = Some(value.into());
        self
    }

    /// Override the server URL for this request.
    pub fn server_url(mut self, url: impl Into<String>) -> Self {
        self.server_url = Some(url.into());
        self
    }

    /// Override the timeout for this request.
    pub fn timeout(mut self, timeout: std::time::Duration) -> Self {
        self.timeout = Some(timeout);
        self
    }

    /// Send the request.
    pub async fn send(self) -> Result<PartDeleteResponse> {
        let number = self.number
            .ok_or_else(|| Error::Validation(
                "missing required path parameter: number".to_string(),
            ))?;
        let number_encoded = utf8_percent_encode(&number, URI_COMPONENT).to_string();

        let base_url = self.server_url
            .as_deref()
            .unwrap_or(&self.client.config.base_url);

        let url = format!(
            "{}/v2/parts/{number}",
            base_url,
            number = number_encoded,
        );

        let mut request = self.client.http.request(
            reqwest::Method::DELETE,
            &url,
        );

        if let Some(timeout) = self.timeout {
            request = request.timeout(timeout);
        }



        let response = self.client.execute(
            request,
            "part-delete",
            base_url,
        ).await?;
        let result: PartDeleteResponse = response.json().await?;
        Ok(result)
    }
}

// ---------------------------------------------------------------------------
// UpdateBuilder
// ---------------------------------------------------------------------------

/// Builder for [`PartsClient::update`].
///
/// # Example
///
/// ```no_run
/// use tofupilot::TofuPilot;
///
/// # #[tokio::main]
/// # async fn main() -> tofupilot::Result<()> {
/// let client = TofuPilot::new("your-api-key");
/// let response = client.parts().update()
///     .send()
///     .await?;
/// # Ok(())
/// # }
/// ```
#[derive(Debug)]
pub struct UpdateBuilder<'a> {
    client: &'a TofuPilot,
    number: Option<String>,
    new_number: Option<String>,
    name: Option<String>,
    server_url: Option<String>,
    timeout: Option<std::time::Duration>,
}

impl<'a> UpdateBuilder<'a> {
    pub(crate) fn new(client: &'a TofuPilot) -> Self {
        Self {
            client,
            number: None,
            new_number: None,
            name: None,
            server_url: None,
            timeout: None,
        }
    }

    /// Set the `number` path parameter.
    ///
    /// Part number of the part to update.
    pub fn number(mut self, value: impl Into<String>) -> Self {
        self.number = Some(value.into());
        self
    }

    /// Set the `new_number` field.
    ///
    /// New unique identifier number for the part.
    pub fn new_number(mut self, value: impl Into<String>) -> Self {
        self.new_number = Some(value.into());
        self
    }

    /// Set the `name` field.
    ///
    /// New human-readable name for the part.
    pub fn name(mut self, value: impl Into<String>) -> Self {
        self.name = Some(value.into());
        self
    }

    /// Set the full request body (alternative to setting individual fields).
    pub fn body(mut self, body: PartUpdateRequestBody) -> Self {
        if body.new_number.is_some() {
            self.new_number = body.new_number;
        }
        if body.name.is_some() {
            self.name = body.name;
        }
        self
    }

    /// Override the server URL for this request.
    pub fn server_url(mut self, url: impl Into<String>) -> Self {
        self.server_url = Some(url.into());
        self
    }

    /// Override the timeout for this request.
    pub fn timeout(mut self, timeout: std::time::Duration) -> Self {
        self.timeout = Some(timeout);
        self
    }

    /// Send the request.
    pub async fn send(self) -> Result<PartUpdateResponse> {
        let number = self.number
            .ok_or_else(|| Error::Validation(
                "missing required path parameter: number".to_string(),
            ))?;
        let number_encoded = utf8_percent_encode(&number, URI_COMPONENT).to_string();

        let base_url = self.server_url
            .as_deref()
            .unwrap_or(&self.client.config.base_url);

        let url = format!(
            "{}/v2/parts/{number}",
            base_url,
            number = number_encoded,
        );

        let mut request = self.client.http.request(
            reqwest::Method::PATCH,
            &url,
        );

        if let Some(timeout) = self.timeout {
            request = request.timeout(timeout);
        }


        let body = PartUpdateRequestBody {
            new_number: self.new_number,
            name: self.name,
        };
        request = request.json(&body);

        let response = self.client.execute(
            request,
            "part-update",
            base_url,
        ).await?;
        let result: PartUpdateResponse = response.json().await?;
        Ok(result)
    }
}

