import { invoke } from '@tauri-apps/api/core'
import { listen } from '@tauri-apps/api/event'
import type { WorkflowRecord, WorkflowEventPayload } from './types'

export const workflowApi = {
  /**
   * 触发工作流执行，返回 execution_id。
   *
   * F-260616-06 阶段2(②-2): taskId/targetStatus 可选,同时传时工作流完成/失败联动推进任务。
   * B-260615-34:Tauri 2 IPC 不转 camelCase,snake_case 对齐后端 workflow.rs。
   */
  run(
    name: string,
    dag: unknown,
    config?: Record<string, unknown>,
    taskId?: string,
    targetStatus?: string,
  ): Promise<string> {
    return invoke('run_workflow', {
      name,
      dag,
      config: config ?? {},
      task_id: taskId,
      target_status: targetStatus,
    })
  },

  listExecutions(): Promise<WorkflowRecord[]> {
    return invoke('list_workflow_executions')
  },

  getExecution(id: string): Promise<WorkflowRecord | null> {
    return invoke('get_workflow_execution', { id })
  },

  /** 监听工作流实时事件，返回 unlisten 函数 */
  onEvent(callback: (payload: WorkflowEventPayload) => void): Promise<() => void> {
    return listen<WorkflowEventPayload>('workflow-event', (event) => {
      callback(event.payload)
    })
  },

  /**
   * 发送人工审批响应。
   *
   * 统一以 decisions 数组表达选择,按 select_type 判定单/多选:
   * - 单选:decision 取 decisions[0];
   * - 多选:decisions 透传全量,decision 取首项作占位(后端按 decisions 走)。
   * options 透传闭环后端校验(R-PD-5)。
   * B-260615-34:Tauri 2 IPC 不转 camelCase,snake_case 对齐后端 workflow.rs。
   */
  approveHumanApproval(params: {
    execution_id: string
    node_id: string
    decision: string
    comment?: string
    options: string[]
    decisions: string[]
    select_type: 'single' | 'multiple'
  }): Promise<void> {
    return invoke('approve_human_approval', params)
  },

  /** 取消当前待审批节点(置节点 Cancelled) */
  cancelHumanApproval(params: { execution_id: string; node_id: string }): Promise<void> {
    return invoke('cancel_workflow_node', params)
  },
}
