// 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 Procedures API.
#[derive(Debug, Clone)]
pub struct ProceduresClient<'a> {
    pub(crate) client: &'a TofuPilot,
}

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

    /// List and filter procedures
    ///
    /// Retrieve procedures with optional filtering and search. Returns procedure data including creator and linked repository.
    pub fn list(&self) -> ListBuilder<'a> {
        ListBuilder::new(self.client)
    }

    /// Create procedure
    ///
    /// Create a new test procedure that can be used to organize and track test runs. The procedure serves as a template or framework for organizing test execution.
    pub fn create(&self) -> CreateBuilder<'a> {
        CreateBuilder::new(self.client)
    }

    /// Get procedure
    ///
    /// Retrieve a single procedure by ID, including recent test runs, linked stations, and version history.
    pub fn get(&self) -> GetBuilder<'a> {
        GetBuilder::new(self.client)
    }

    /// Delete procedure
    ///
    /// Permanently delete a procedure, removing all associated runs, phases, measurements, and attachments.
    pub fn delete(&self) -> DeleteBuilder<'a> {
        DeleteBuilder::new(self.client)
    }

    /// Update procedure
    ///
    /// Update a test procedure's name or configuration. The procedure is identified by its unique ID in the URL path. Only provided fields are modified.
    pub fn update(&self) -> UpdateBuilder<'a> {
        UpdateBuilder::new(self.client)
    }

}

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

/// Builder for [`ProceduresClient::list`].
///
/// # Example
///
/// ```no_run
/// use tofupilot::TofuPilot;
///
/// # #[tokio::main]
/// # async fn main() -> tofupilot::Result<()> {
/// let client = TofuPilot::new("your-api-key");
/// let response = client.procedures().list()
///     .send()
///     .await?;
/// # Ok(())
/// # }
/// ```
#[derive(Debug)]
pub struct ListBuilder<'a> {
    client: &'a TofuPilot,
    limit: Option<i64>,
    cursor: Option<f64>,
    search_query: Option<String>,
    created_after: Option<chrono::DateTime<chrono::Utc>>,
    created_before: Option<chrono::DateTime<chrono::Utc>>,
    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,
            created_after: None,
            created_before: None,
            server_url: None,
            timeout: None,
        }
    }

    /// Set the `limit` query parameter.
    ///
    /// Maximum number of procedures to return per 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<f64>) -> 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 `created_after` query parameter.
    pub fn created_after(mut self, value: impl Into<chrono::DateTime<chrono::Utc>>) -> Self {
        self.created_after = Some(value.into());
        self
    }

    /// Set the `created_before` query parameter.
    pub fn created_before(mut self, value: impl Into<chrono::DateTime<chrono::Utc>>) -> Self {
        self.created_before = 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<ProcedureListResponse> {

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

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

        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.created_after {
            request = request.query(&[("created_after", val.to_rfc3339_opts(chrono::SecondsFormat::Millis, true))]);
        }
        if let Some(ref val) = self.created_before {
            request = request.query(&[("created_before", val.to_rfc3339_opts(chrono::SecondsFormat::Millis, true))]);
        }


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

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

/// Builder for [`ProceduresClient::create`].
///
/// # Example
///
/// ```no_run
/// use tofupilot::TofuPilot;
///
/// # #[tokio::main]
/// # async fn main() -> tofupilot::Result<()> {
/// let client = TofuPilot::new("your-api-key");
/// let response = client.procedures().create()
///     .name("value")
///     .send()
///     .await?;
/// # Ok(())
/// # }
/// ```
#[derive(Debug)]
pub struct CreateBuilder<'a> {
    client: &'a TofuPilot,
    name: 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,
            name: None,
            server_url: None,
            timeout: None,
        }
    }

    /// Set the `name` field.
    ///
    /// Name of the procedure. Must be unique within the organization.
    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: ProcedureCreateRequest) -> Self {
        self.name = Some(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<ProcedureCreateResponse> {

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

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

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

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


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

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

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

/// Builder for [`ProceduresClient::get`].
///
/// # Example
///
/// ```no_run
/// use tofupilot::TofuPilot;
///
/// # #[tokio::main]
/// # async fn main() -> tofupilot::Result<()> {
/// let client = TofuPilot::new("your-api-key");
/// let response = client.procedures().get()
///     .id("value")
///     .send()
///     .await?;
/// # Ok(())
/// # }
/// ```
#[derive(Debug)]
pub struct GetBuilder<'a> {
    client: &'a TofuPilot,
    id: 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,
            id: None,
            server_url: None,
            timeout: None,
        }
    }

    /// Set the `id` path parameter.
    ///
    /// Unique identifier of the procedure to retrieve.
    pub fn id(mut self, value: impl Into<String>) -> Self {
        self.id = 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<ProcedureGetResponse> {
        let id = self.id
            .ok_or_else(|| Error::Validation(
                "missing required path parameter: id".to_string(),
            ))?;
        let id_encoded = utf8_percent_encode(&id, URI_COMPONENT).to_string();

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

        let url = format!(
            "{}/v2/procedures/{id}",
            base_url,
            id = id_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,
            "procedure-get",
            base_url,
        ).await?;
        let result: ProcedureGetResponse = response.json().await?;
        Ok(result)
    }
}

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

/// Builder for [`ProceduresClient::delete`].
///
/// # Example
///
/// ```no_run
/// use tofupilot::TofuPilot;
///
/// # #[tokio::main]
/// # async fn main() -> tofupilot::Result<()> {
/// let client = TofuPilot::new("your-api-key");
/// let response = client.procedures().delete()
///     .id("value")
///     .send()
///     .await?;
/// # Ok(())
/// # }
/// ```
#[derive(Debug)]
pub struct DeleteBuilder<'a> {
    client: &'a TofuPilot,
    id: 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,
            id: None,
            server_url: None,
            timeout: None,
        }
    }

    /// Set the `id` path parameter.
    ///
    /// Unique identifier of the procedure to delete.
    pub fn id(mut self, value: impl Into<String>) -> Self {
        self.id = 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<ProcedureDeleteResponse> {
        let id = self.id
            .ok_or_else(|| Error::Validation(
                "missing required path parameter: id".to_string(),
            ))?;
        let id_encoded = utf8_percent_encode(&id, URI_COMPONENT).to_string();

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

        let url = format!(
            "{}/v2/procedures/{id}",
            base_url,
            id = id_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,
            "procedure-delete",
            base_url,
        ).await?;
        let result: ProcedureDeleteResponse = response.json().await?;
        Ok(result)
    }
}

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

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

impl<'a> UpdateBuilder<'a> {
    pub(crate) fn new(client: &'a TofuPilot) -> Self {
        Self {
            client,
            id: None,
            name: None,
            production_branch: None,
            auto_push_enabled: None,
            excluded_branch_patterns: None,
            root_directory: None,
            server_url: None,
            timeout: None,
        }
    }

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

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

    /// Set the `production_branch` field.
    ///
    /// Branch treated as production. Pushes to this branch deploy as production; every other branch deploys as preview. Null = no branch promoted to production.
    pub fn production_branch(mut self, value: impl Into<String>) -> Self {
        self.production_branch = Some(NullableField::Value(value.into()));
        self
    }

    /// Explicitly set `production_branch` to null.
    pub fn production_branch_null(mut self) -> Self {
        self.production_branch = Some(NullableField::Null);
        self
    }

    /// Set the `auto_push_enabled` field.
    ///
    /// Master switch for auto-pushing builds to linked stations. Build artifacts are always recorded; this only gates the station fan-out.
    pub fn auto_push_enabled(mut self, value: impl Into<bool>) -> Self {
        self.auto_push_enabled = Some(value.into());
        self
    }

    /// Set the `excluded_branch_patterns` field.
    ///
    /// Branches matching any of these patterns (exact name or minimatch glob, e.g. "renovate/*") skip preview deployments. Empty array = no exclusions.
    pub fn excluded_branch_patterns(mut self, value: impl Into<Vec<String>>) -> Self {
        self.excluded_branch_patterns = Some(value.into());
        self
    }

    /// Set the `root_directory` field.
    ///
    /// Path within the linked repo to the directory holding this procedure's `pyproject.toml` (and `procedure.yaml` for framework procedures). Empty/null = repo root.
    pub fn root_directory(mut self, value: impl Into<String>) -> Self {
        self.root_directory = Some(NullableField::Value(value.into()));
        self
    }

    /// Explicitly set `root_directory` to null.
    pub fn root_directory_null(mut self) -> Self {
        self.root_directory = Some(NullableField::Null);
        self
    }

    /// Set the full request body (alternative to setting individual fields).
    pub fn body(mut self, body: ProcedureUpdateRequestBody) -> Self {
        if body.name.is_some() {
            self.name = body.name;
        }
        self.production_branch = Some(body.production_branch);
        if body.auto_push_enabled.is_some() {
            self.auto_push_enabled = body.auto_push_enabled;
        }
        if body.excluded_branch_patterns.is_some() {
            self.excluded_branch_patterns = body.excluded_branch_patterns;
        }
        self.root_directory = Some(body.root_directory);
        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<ProcedureUpdateResponse> {
        let id = self.id
            .ok_or_else(|| Error::Validation(
                "missing required path parameter: id".to_string(),
            ))?;
        let id_encoded = utf8_percent_encode(&id, URI_COMPONENT).to_string();

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

        let url = format!(
            "{}/v2/procedures/{id}",
            base_url,
            id = id_encoded,
        );

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

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


        let body = ProcedureUpdateRequestBody {
            name: self.name,
            production_branch: self.production_branch.unwrap_or(NullableField::Absent),
            auto_push_enabled: self.auto_push_enabled,
            excluded_branch_patterns: self.excluded_branch_patterns,
            root_directory: self.root_directory.unwrap_or(NullableField::Absent),
        };
        request = request.json(&body);

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

