import axios from 'axios'
import { deleteRecords, getRecord } from './common'

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 BatchDeleteResponse {
  success: boolean
  message: string
  message_params?: Record<string, number>
  success_count: number
  failed_jobs: string[]
}

/**
 * 获取Local Job列表
 */
export async function getLocalJobList(
  page: number = 1,
  pageLength: number = 20,
  orderBy: string = 'modified desc',
  filters?: any[]
): Promise<LocalJobListResponse> {
  try {
    // Local Job is a virtual pagetype, use dedicated action endpoint instead of generic REST API
    const response = await axios.get(
      '/api/action/jingrow.core.pagetype.local_job.local_job.get_local_job_list',
      {
        params: {
          limit_start: (page - 1) * pageLength,
          limit_page_length: pageLength,
          order_by: orderBy
        }
      }
    )
    
    const items = response.data?.message || []
    return {
      success: true,
      items: items,
      total: items.length, // Virtual pagetype returns filtered list only
      page: page,
      page_length: pageLength
    }
  } catch (error: any) {
    throw new Error(error.response?.data?.message || error.message || 'Failed to fetch local jobs')
  }
}

/**
 * 获取Local Job详情
 */
export async function getLocalJobDetail(jobId: string): Promise<LocalJobDetailResponse> {
  const result = await getRecord('Local Job', jobId)
  
  if (result.success) {
    return {
      success: true,
      data: result.data
    }
  } else {
    throw new Error(result.message || 'Failed to fetch local job detail')
  }
}

/**
 * 停止Local Job
 */
export async function stopLocalJob(jobId: string): Promise<{ success: boolean; message: string }> {
  try {
    const response = await axios.post(
      '/api/action/jingrow.core.pagetype.local_job.local_job.stop_job',
      {
        job_id: jobId
      }
    )
    
    return {
      success: true,
      message: response.data?.message || 'Job stopped successfully'
    }
  } catch (error: any) {
    return {
      success: false,
      message: error.response?.data?.message || error.message || 'Failed to stop job'
    }
  }
}

/**
 * 删除Local Job
 */
export async function deleteLocalJob(jobId: string): Promise<{ success: boolean; message: string }> {
  const result = await deleteRecords('Local Job', [jobId])
  
  return {
    success: result.success,
    message: result.message || (result.success ? 'Job deleted successfully' : 'Failed to delete job')
  }
}

/**
 * 批量删除Local Jobs
 */
export async function batchDeleteLocalJobs(jobIds: string[]): Promise<BatchDeleteResponse> {
  const result = await deleteRecords('Local Job', jobIds)
  
  return {
    success: result.success,
    message: result.message || (result.success ? 'Jobs deleted successfully' : 'Failed to delete jobs'),
    success_count: result.success ? jobIds.length : 0,
    failed_jobs: result.success ? [] : jobIds
  }
}

