/**
 * 定时任务管理 API 调用。
 */

import { apiClient } from './client';

/** 定时任务信息 */
export interface TriggerJob {
  id: number;
  job_type: string;
  job_name: string;
  trigger_condition: string;
  trigger_config: Record<string, unknown> | null;
  last_run_at: string | null;
  next_run_at: string | null;
  status: string;
  description: string | null;
  last_error: string | null;
  created_at: string | null;
}

/** 手动执行结果 */
export interface RunJobResult {
  success: boolean;
  message: string;
}

/** 获取所有定时任务 */
export async function fetchTriggerJobs(): Promise<TriggerJob[]> {
  const { data } = await apiClient.get<TriggerJob[]>('/trigger-jobs');
  return data;
}

/** 手动执行指定任务 */
export async function runTriggerJob(jobId: number): Promise<RunJobResult> {
  const { data } = await apiClient.post<RunJobResult>(`/trigger-jobs/${jobId}/run`);
  return data;
}

/** 触发器配置更新请求 */
export interface UpdateTriggerConfigReq {
  cron_expression?: string;
  interval_seconds?: number;
}

/** 更新触发器配置（cron 表达式或间隔秒数） */
export async function updateTriggerConfig(
  jobId: number,
  body: UpdateTriggerConfigReq,
): Promise<TriggerJob> {
  const { data } = await apiClient.patch<TriggerJob>(
    `/trigger-jobs/${jobId}/config`,
    body,
  );
  return data;
}

/** 【测试】清空所有 coach_tasks */
export async function clearAllTasks(): Promise<RunJobResult> {
  const { data } = await apiClient.delete<RunJobResult>('/admin/task-engine/clear-all-tasks');
  return data;
}
