import { deleteRecords, createRecord, updateRecord, getRecord, getRecords } from './common'

// 获取 Scheduled Job 列表 - 使用通用函数
export const getScheduledJobs = async (page: number = 1, pageSize: number = 10, filters: any[] = []): Promise<any> => {
  const fields = [
    'name', 'method', 'frequency', 'cron_format', 
    'stopped', 'create_log', 'last_execution', 
    'server_script', 'scheduler_event', 'creation', 'modified'
  ]
  
  const result = await getRecords(
    'Local Scheduled Job',
    filters,
    fields,
    'modified desc',
    (page - 1) * pageSize,
    pageSize
  )
  
  if (!result.success) {
    throw new Error(result.message || '获取 Scheduled Job 列表失败')
  }
  
  return {
    items: result.data || [],
    total: result.total || 0
  }
}

// 获取单个 Scheduled Job 详情 - 使用通用函数
export const getScheduledJobDetail = async (name: string): Promise<any> => {
  const result = await getRecord('Local Scheduled Job', name)
  if (!result.success) {
    throw new Error(result.message || '获取 Scheduled Job 详情失败')
  }
  return result.data
}

// 切换 Scheduled Job 状态 - 使用通用函数
export const toggleScheduledJobStatus = async (name: string): Promise<{ success: boolean; message?: string }> => {
  try {
    // 先获取当前状态
    const currentData = await getRecord('Local Scheduled Job', name)
    if (!currentData.success) {
      throw new Error('获取当前状态失败')
    }
    
    const currentStopped = currentData.data.stopped || 0
    const newStopped = currentStopped ? 0 : 1
    
    // 更新状态 - 使用通用函数
    const result = await updateRecord('Local Scheduled Job', name, { stopped: newStopped })
    
    if (result.success) {
      return { 
        success: true, 
        message: `状态已更新为${newStopped ? '停止' : '运行'}` 
      }
    } else {
      throw new Error(result.message || '更新状态失败')
    }
  } catch (error: any) {
    console.error('Error in toggleScheduledJobStatus:', error)
    return { 
      success: false, 
      message: error.message || '更新状态失败' 
    }
  }
}

// 创建 Scheduled Job - 使用通用函数
export const createScheduledJob = async (data: Record<string, any>): Promise<{ success: boolean; data?: any; message?: string }> => {
  return createRecord('Local Scheduled Job', data)
}

// 更新 Scheduled Job - 使用通用函数
export const updateScheduledJob = async (name: string, data: Record<string, any>): Promise<{ success: boolean; data?: any; message?: string }> => {
  return updateRecord('Local Scheduled Job', name, data)
}

// 删除 Scheduled Job - 使用通用函数
export const deleteScheduledJobs = async (names: string[]): Promise<{ success: boolean; message?: string }> => {
  return deleteRecords('Local Scheduled Job', names)
}
