// Code generated by oagen. DO NOT EDIT.

use crate::client::Retab;
#[allow(unused_imports)]
use crate::enums::*;
use crate::error::Error;
#[allow(unused_imports)]
use crate::models::*;
use serde::Serialize;

pub struct WorkflowRunsApi<'a> {
    pub(crate) client: &'a Retab,
}

#[derive(Debug, Clone, Serialize)]
pub struct ListParams {
    /// Filter by workflow ID
    #[serde(skip_serializing_if = "Option::is_none")]
    pub workflow_id: Option<String>,
    /// Filter by single run status (deprecated, use 'statuses')
    #[serde(skip_serializing_if = "Option::is_none")]
    pub status: Option<WorkflowRunsStatus>,
    /// Filter by multiple statuses (comma-separated: pending,queued,running,completed,error,failed,awaiting_review,cancelled)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub statuses: Option<String>,
    /// Exclude runs with this status
    #[serde(skip_serializing_if = "Option::is_none")]
    pub exclude_status: Option<WorkflowRunsExcludeStatus>,
    /// Filter by single trigger type (deprecated, use 'trigger_types')
    #[serde(skip_serializing_if = "Option::is_none")]
    pub trigger_type: Option<WorkflowRunsTriggerType>,
    /// Filter by multiple trigger types (comma-separated: manual,api,schedule,webhook,email,restart)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub trigger_types: Option<String>,
    /// Filter runs created on or after this date (YYYY-MM-DD)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub from_date: Option<String>,
    /// Filter runs created on or before this date (YYYY-MM-DD)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub to_date: Option<String>,
    /// Filter runs with duration >= this value in milliseconds
    #[serde(skip_serializing_if = "Option::is_none")]
    pub min_duration_ms: Option<i64>,
    /// Filter runs with duration <= this value in milliseconds
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_duration_ms: Option<i64>,
    /// Search by run ID (partial match)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub search: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub before: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub after: Option<String>,
    /// Items per page
    ///
    /// Defaults to `20`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub limit: Option<i64>,
    /// Defaults to `desc`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub order: Option<WorkflowRunsOrder>,
    /// Defaults to `timing.created_at`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub sort_by: Option<String>,
}

impl Default for ListParams {
    #[allow(deprecated)]
    fn default() -> Self {
        Self {
            workflow_id: Default::default(),
            status: Default::default(),
            statuses: Default::default(),
            exclude_status: Default::default(),
            trigger_type: Default::default(),
            trigger_types: Default::default(),
            from_date: Default::default(),
            to_date: Default::default(),
            min_duration_ms: Default::default(),
            max_duration_ms: Default::default(),
            search: Default::default(),
            before: Default::default(),
            after: Default::default(),
            limit: Some(20),
            order: Some(WorkflowRunsOrder::Desc),
            sort_by: Some("timing.created_at".to_string()),
        }
    }
}

#[derive(Debug, Clone, Serialize)]
pub struct CreateParams {
    /// Request body sent with this call.
    ///
    /// Required.
    #[serde(skip)]
    pub body: CreateWorkflowRunRequest,
}

impl CreateParams {
    /// Construct a new `CreateParams` with the required fields set.
    #[allow(deprecated)]
    pub fn new(body: CreateWorkflowRunRequest) -> Self {
        Self { body }
    }
}

#[derive(Debug, Clone, Serialize)]
pub struct ExportParams {
    /// Request body sent with this call.
    ///
    /// Required.
    #[serde(skip)]
    pub body: WorkflowExportPayloadRequest,
}

impl ExportParams {
    /// Construct a new `ExportParams` with the required fields set.
    #[allow(deprecated)]
    pub fn new(body: WorkflowExportPayloadRequest) -> Self {
        Self { body }
    }
}

#[derive(Debug, Clone, Default, Serialize)]
pub struct CancelParams {
    /// Request body sent with this call.
    #[serde(skip)]
    pub body: Option<CancelWorkflowRequest>,
}

impl<'a> WorkflowRunsApi<'a> {
    /// List Workflow Runs
    ///
    /// List workflow runs with pagination and optional filters.
    pub async fn list(&self, params: ListParams) -> Result<WorkflowRunList, Error> {
        self.list_with_options(params, None).await
    }

    /// Variant of [`Self::list`] that accepts per-request [`crate::RequestOptions`].
    pub async fn list_with_options(
        &self,
        params: ListParams,
        options: Option<&crate::RequestOptions>,
    ) -> Result<WorkflowRunList, Error> {
        let path = "/v1/workflows/runs".to_string();
        let method = http::Method::GET;
        self.client
            .request_with_query_opts(method, &path, &params, options)
            .await
    }

    /// Returns an async [`futures_util::Stream`] that yields every `WorkflowRun`
    /// across all pages, advancing the `after` cursor under the hood.
    ///
    /// ```ignore
    /// use futures_util::TryStreamExt;
    /// let all: Vec<WorkflowRun> = self
    ///     .list_auto_paging(params)
    ///     .try_collect()
    ///     .await?;
    /// ```
    pub fn list_auto_paging(
        &self,
        params: ListParams,
    ) -> impl futures_util::Stream<Item = Result<WorkflowRun, Error>> + '_ {
        crate::pagination::auto_paginate_pages(move |after| {
            let mut params = params.clone();
            params.after = after;
            async move {
                let page = self.list(params).await?;
                Ok((page.data, page.list_metadata.after))
            }
        })
    }

    /// Create Workflow Run Route
    ///
    /// Create a workflow run.
    ///
    /// Two creation paths, discriminated by ``restart_of``:
    ///
    /// - ``restart_of`` is ``None``: fresh run. ``workflow_id`` is required;
    /// ``documents``, ``json_inputs``, and ``version`` carry the run inputs.
    /// - ``restart_of`` is set: restart of an existing run. The source run's
    /// inputs are inherited; ``config_source`` selects ``draft`` vs
    /// ``published`` config for the new run.
    ///
    /// The shape of the request enforces these invariants — see
    /// ``CreateWorkflowRunRequest``.
    pub async fn create(&self, params: CreateParams) -> Result<WorkflowRun, Error> {
        self.create_with_options(params, None).await
    }

    /// Variant of [`Self::create`] that accepts per-request [`crate::RequestOptions`].
    pub async fn create_with_options(
        &self,
        params: CreateParams,
        options: Option<&crate::RequestOptions>,
    ) -> Result<WorkflowRun, Error> {
        let path = "/v1/workflows/runs".to_string();
        let method = http::Method::POST;
        self.client
            .request_with_body_opts(method, &path, &params, Some(&params.body), options)
            .await
    }

    /// Get Workflow Export Payload
    ///
    /// Build CSV content for workflow run exports.
    pub async fn export(
        &self,
        params: ExportParams,
    ) -> Result<WorkflowExportPayloadResponse, Error> {
        self.export_with_options(params, None).await
    }

    /// Variant of [`Self::export`] that accepts per-request [`crate::RequestOptions`].
    pub async fn export_with_options(
        &self,
        params: ExportParams,
        options: Option<&crate::RequestOptions>,
    ) -> Result<WorkflowExportPayloadResponse, Error> {
        let path = "/v1/workflows/runs/export".to_string();
        let method = http::Method::POST;
        self.client
            .request_with_body_opts(method, &path, &params, Some(&params.body), options)
            .await
    }

    /// Get Workflow Run
    ///
    /// Get a single workflow run by ID.
    pub async fn get(&self, run_id: &str) -> Result<WorkflowRun, Error> {
        self.get_with_options(run_id, None).await
    }

    /// Variant of [`Self::get`] that accepts per-request [`crate::RequestOptions`].
    pub async fn get_with_options(
        &self,
        run_id: &str,
        options: Option<&crate::RequestOptions>,
    ) -> Result<WorkflowRun, Error> {
        let run_id = crate::client::path_segment(run_id);
        let path = format!("/v1/workflows/runs/{run_id}");
        let method = http::Method::GET;
        self.client
            .request_with_query_opts(method, &path, &(), options)
            .await
    }

    /// Delete Workflow Run
    ///
    /// Delete a workflow run and its associated step data.
    pub async fn delete(&self, run_id: &str) -> Result<(), Error> {
        self.delete_with_options(run_id, None).await
    }

    /// Variant of [`Self::delete`] that accepts per-request [`crate::RequestOptions`].
    pub async fn delete_with_options(
        &self,
        run_id: &str,
        options: Option<&crate::RequestOptions>,
    ) -> Result<(), Error> {
        let run_id = crate::client::path_segment(run_id);
        let path = format!("/v1/workflows/runs/{run_id}");
        let method = http::Method::DELETE;
        self.client
            .request_with_query_opts_empty(method, &path, &(), options)
            .await
    }

    /// Cancel Workflow Run
    ///
    /// Cancel a pending, running, or waiting workflow run.
    pub async fn cancel(
        &self,
        run_id: &str,
        params: CancelParams,
    ) -> Result<CancelWorkflowResponse, Error> {
        self.cancel_with_options(run_id, params, None).await
    }

    /// Variant of [`Self::cancel`] that accepts per-request [`crate::RequestOptions`].
    pub async fn cancel_with_options(
        &self,
        run_id: &str,
        params: CancelParams,
        options: Option<&crate::RequestOptions>,
    ) -> Result<CancelWorkflowResponse, Error> {
        let run_id = crate::client::path_segment(run_id);
        let path = format!("/v1/workflows/runs/{run_id}/cancel");
        let method = http::Method::POST;
        self.client
            .request_with_body_opts(method, &path, &params, params.body.as_ref(), options)
            .await
    }
}
