import request from '@/utils/http'

export interface ScheduledTask {
  id: string; code: string; name: string; description: string
  cron_expression: string; timezone: string; target_type: 'application' | 'digital_employee'; target_code: string
  prompt: string; variables: Record<string, unknown>; skill_ids: string[]; mcp_server_ids: string[]
  conversation_id: string; notification_channel_id?: string; has_api_key: boolean; enabled: boolean
  next_run_at?: string; last_run_at?: string; last_status: string; last_error: string; revision: number
}

export interface ScheduledTaskInput {
  code: string; name: string; description: string; cron_expression: string; timezone: string
  target_type: 'application' | 'digital_employee'; target_code: string; prompt: string
  variables: Record<string, unknown>; skill_ids: string[]; mcp_server_ids: string[]
  conversation_id: string; notification_channel_id?: string | null; api_key?: string; enabled: boolean
}

export interface ScheduledTaskRun {
  id: string; task_id: string; task_code: string; trigger_type: string; scheduled_for: string
  status: string; attempts: number; worker_id: string; started_at?: string; finished_at?: string
  response?: Record<string, unknown>; error: string; created_at: string
}

export const fetchScheduledTasks = () => request.get<ScheduledTask[]>({ url: '/api/v1/admin/scheduled-tasks' })
export const createScheduledTask = (data: ScheduledTaskInput) => request.post<ScheduledTask>({ url: '/api/v1/admin/scheduled-tasks', data })
export const updateScheduledTask = (id: string, data: ScheduledTaskInput) => request.put<ScheduledTask>({ url: `/api/v1/admin/scheduled-tasks/${id}`, data })
export const deleteScheduledTask = (id: string) => request.del({ url: `/api/v1/admin/scheduled-tasks/${id}` })
export const startScheduledTask = (id: string) => request.post<ScheduledTask>({ url: `/api/v1/admin/scheduled-tasks/${id}/start` })
export const pauseScheduledTask = (id: string) => request.post<ScheduledTask>({ url: `/api/v1/admin/scheduled-tasks/${id}/pause` })
export const runScheduledTask = (id: string) => request.post<ScheduledTaskRun>({ url: `/api/v1/admin/scheduled-tasks/${id}/run` })
export const fetchScheduledTaskRuns = (id: string) => request.get<ScheduledTaskRun[]>({ url: `/api/v1/admin/scheduled-tasks/${id}/runs` })
