import { http } from '@/api/request'
import type { Attachment, FlowInstance, ProcessProgress } from '@/types/flow'
import type { PageQuery, PageResult } from '@/types/api'
import type { AxiosRequestConfig } from 'axios'

export function listMyInstance(params?: PageQuery): Promise<PageResult<FlowInstance>> {
  return http.get('/flow/instance/mine', { params })
}

export function listInstance(
  params?: PageQuery & {
    applicantName?: string
    processName?: string
    definitionName?: string
    processDefinitionId?: number
    currentNodeId?: string
  }
): Promise<PageResult<FlowInstance>> {
  return http.get('/flow/instance/page', { params })
}

export function startInstance(
  processDefinitionId: number,
  title?: string,
  formData?: Record<string, unknown>,
  attachmentUrls?: string
): Promise<void> {
  return http.post('/flow/instance/start', {
    processDefinitionId,
    title,
    formData: formData ? JSON.stringify(formData) : undefined,
    attachmentUrls,
  })
}

export function getInstance(id: number): Promise<FlowInstance> {
  return http.get(`/flow/instance/${id}`)
}

export function getProgress(id: number, config?: AxiosRequestConfig): Promise<ProcessProgress> {
  return http.get(`/flow/instance/${id}/progress`, config)
}

export function participatedList(params?: PageQuery): Promise<PageResult<FlowInstance>> {
  return http.get('/flow/instance/participated', { params })
}

export function revokeInstance(id: number): Promise<void> {
  return http.post(`/flow/instance/${id}/revoke`)
}

export function batchRevokeInstance(ids: number[]): Promise<void> {
  return http.post('/flow/instance/batch-revoke', ids)
}

export function deleteInstance(id: number): Promise<void> {
  return http.delete(`/flow/instance/${id}`)
}

export function batchDeleteInstance(ids: number[]): Promise<void> {
  return http.post('/flow/instance/batch-delete', ids)
}

export function getInstanceAttachments(id: number): Promise<Attachment[]> {
  return http.get(`/flow/instance/${id}/attachments`)
}

export function updateInstanceFormData(id: number, formData: Record<string, unknown>): Promise<void> {
  return http.post(`/flow/instance/${id}/form-data`, {
    formData: JSON.stringify(formData),
  })
}

export function migrateInstances(fromDefinitionId: number, toDefinitionId: number): Promise<{ migratedCount: number }> {
  return http.post('/flow/instance/migrate-all', null, { params: { fromDefinitionId, toDefinitionId } })
}
