/**
 * 安全测试定时任务管理 API 接口
 *
 * @module api/securityScheduledTasks
 * @author czj
 * @date 2026-08-19
 */

import request from '@/utils/request'

/** 安全测试定时任务数据结构 */
export interface SecurityScheduledTask {
  id: string
  name: string
  enabled: boolean
  module_ids: string[]
  module_names: string[]
  config_id: string
  config_name: 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 SecurityScheduledTaskPayload {
  name: string
  module_ids: string[]
  config_id: 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 securityScheduledTaskApi = {
  /** 获取安全测试定时任务列表 */
  async list(): Promise<{ total: number; items: SecurityScheduledTask[] }> {
    const response = await request.get('/api/security/scheduled-tasks')
    return response as any
  },

  /** 创建安全测试定时任务 */
  async create(data: SecurityScheduledTaskPayload): Promise<SecurityScheduledTask> {
    const response = await request.post('/api/security/scheduled-tasks', data)
    return response as any
  },

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

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

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

  /** 启用 / 停用 */
  async toggle(id: string, enabled: boolean): Promise<SecurityScheduledTask> {
    const response = await request.post(`/api/security/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/security/scheduled-tasks/${id}/runs`, { params })
    return response as any
  },
}