/**
 * 定时任务管理 API 接口
 *
 * @module api/scheduledTasks
 * @author czj
 * @date 2026-08-19
 */

import request from '@/utils/request'

/** 定时任务数据结构 */
export interface ScheduledTask {
  id: string
  name: string
  enabled: boolean
  module_ids: string[]
  module_names: string[]
  schedule_type: string
  interval_value: number
  interval_unit: string
  run_time: string
  weekdays: number[]
  auto_report: boolean
  schedule_description: string
  last_run_at: string | null
  next_run_at: string | null
  run_count: number
  created_at: string | null
  updated_at: string | null
}

/** 创建/编辑定时任务请求体 */
export interface ScheduledTaskPayload {
  name: string
  module_ids: string[]
  schedule_type: 'interval' | 'daily' | 'weekly'
  interval_value?: number
  interval_unit?: 'minutes' | 'hours' | 'days'
  run_time?: string
  weekdays?: number[]
  auto_report?: boolean
  enabled?: boolean
}

/**
 * 定时任务管理 API 服务
 */
export const scheduledTaskApi = {
  /** 获取定时任务列表 */
  async list(): Promise<{ total: number; items: ScheduledTask[] }> {
    const response = await request.get('/api/scheduled-tasks')
    return response as any
  },

  /** 创建定时任务 */
  async create(data: ScheduledTaskPayload): Promise<ScheduledTask> {
    const response = await request.post('/api/scheduled-tasks', data)
    return response as any
  },

  /** 更新定时任务 */
  async update(id: string, data: Partial<ScheduledTaskPayload>): Promise<ScheduledTask> {
    const response = await request.put(`/api/scheduled-tasks/${id}`, data)
    return response as any
  },

  /** 删除定时任务（不影响已产生的执行记录与报告） */
  async remove(id: string): Promise<void> {
    await request.delete(`/api/scheduled-tasks/${id}`)
  },

  /** 立即执行 */
  async run(id: string): Promise<{ message: string; task_id: string }> {
    const response = await request.post(`/api/scheduled-tasks/${id}/run`)
    return response as any
  },

  /** 启用 / 停用 */
  async toggle(id: string, enabled: boolean): Promise<ScheduledTask> {
    const response = await request.post(`/api/scheduled-tasks/${id}/toggle`, { enabled })
    return response as any
  },

  /** 运行历史（该任务触发的执行记录） */
  async getRuns(id: string, params?: { skip?: number; limit?: number }): Promise<{ total: number; items: any[] }> {
    const response = await request.get(`/api/scheduled-tasks/${id}/runs`, { params })
    return response as any
  },
}
