import axios from 'axios'

const API_BASE_URL = '/jingrow'

export interface LocalJob {
  name: string
  job_id: string
  queue: string
  job_name: string
  status: 'queued' | 'started' | 'finished' | 'failed' | 'deferred' | 'scheduled' | 'canceled'
  started_at: string
  ended_at: string
  time_taken: string
  exc_info: string
  arguments: string
  timeout: string
  creation: string
  modified: string
  _comment_count: number
  owner: string
  modified_by: string
}

export interface LocalJobListResponse {
  success: boolean
  items: LocalJob[]
  total: number
  page: number
  page_length: number
}

export interface LocalJobDetailResponse {
  success: boolean
  data: LocalJob
}

export interface LocalJobStatsResponse {
  success: boolean
  stats: Record<string, any>
}

export interface BatchDeleteResponse {
  success: boolean
  message: string
  success_count: number
  failed_jobs: string[]
}

/**
 * 获取Local Job列表
 */
export async function getLocalJobList(
  page: number = 1,
  pageLength: number = 20,
  orderBy: string = 'modified desc',
  filters?: string
): Promise<LocalJobListResponse> {
  const params = new URLSearchParams({
    page: page.toString(),
    page_length: pageLength.toString(),
    order_by: orderBy
  })
  
  if (filters) {
    params.append('filters', filters)
  }
  
  const response = await axios.get(`${API_BASE_URL}/local-jobs?${params}`)
  return response.data
}

/**
 * 获取Local Job详情
 */
export async function getLocalJobDetail(jobId: string): Promise<LocalJobDetailResponse> {
  const response = await axios.get(`${API_BASE_URL}/local-jobs/${jobId}`)
  return response.data
}

/**
 * 停止Local Job
 */
export async function stopLocalJob(jobId: string): Promise<{ success: boolean; message: string }> {
  const response = await axios.post(`${API_BASE_URL}/local-jobs/${jobId}/stop`)
  return response.data
}

/**
 * 删除Local Job
 */
export async function deleteLocalJob(jobId: string): Promise<{ success: boolean; message: string }> {
  const response = await axios.delete(`${API_BASE_URL}/local-jobs/${jobId}`)
  return response.data
}

/**
 * 批量删除Local Jobs
 */
export async function batchDeleteLocalJobs(jobIds: string[]): Promise<BatchDeleteResponse> {
  const response = await axios.post(`${API_BASE_URL}/local-jobs/batch-delete`, {
    job_ids: jobIds
  })
  return response.data
}

/**
 * 获取Local Job统计信息
 */
export async function getLocalJobStats(): Promise<LocalJobStatsResponse> {
  const response = await axios.get(`${API_BASE_URL}/local-jobs/stats`)
  return response.data
}
