/**
 * 任务执行相关 API 调用。
 *
 * - submitToQueue：提交任务配置到执行队列
 * - executeDirectly：直接执行任务
 * - fetchQueue：获取当前队列
 * - fetchHistory：获取执行历史
 * - deleteFromQueue：从队列删除任务
 * - cancelExecution：取消执行中的任务
 */

import { apiClient } from './client';
import type { TaskConfig, QueuedTask, ExecutionLog } from '../types';

/** 提交任务配置到执行队列 */
export async function submitToQueue(config: TaskConfig): Promise<{ id: string }> {
  const { data } = await apiClient.post<{ id: string }>('/execution/queue', config);
  return data;
}

/** 直接执行任务（不经过队列） */
export async function executeDirectly(config: TaskConfig): Promise<{ execution_id: string }> {
  const { data } = await apiClient.post<{ execution_id: string }>('/execution/run', config);
  return data;
}

/** 获取当前任务队列 */
export async function fetchQueue(): Promise<QueuedTask[]> {
  const { data } = await apiClient.get<QueuedTask[]>('/execution/queue');
  return data;
}

/** 获取执行历史记录 */
export async function fetchHistory(limit = 50): Promise<ExecutionLog[]> {
  const { data } = await apiClient.get<ExecutionLog[]>('/execution/history', { params: { limit } });
  return data;
}

/** 从队列中删除待执行任务 */
export async function deleteFromQueue(id: string): Promise<void> {
  await apiClient.delete(`/execution/queue/${id}`);
}

/** 取消执行中的任务 */
export async function cancelExecution(id: string): Promise<void> {
  await apiClient.post(`/execution/${id}/cancel`);
}

// CHANGE 2026-03-22 | 重新执行历史任务
/** 重新执行指定的历史任务 */
export async function rerunExecution(id: string): Promise<{ execution_id: string }> {
  const { data } = await apiClient.post<{ execution_id: string }>(`/execution/${id}/rerun`);
  return data;
}

// CHANGE 2026-03-27 | 清理输出目录，每类任务只保留最近 10 个运行记录
/** 清理 EXPORT_ROOT 下旧运行记录 */
export async function cleanupOutput(): Promise<{ task_folders_scanned: number; dirs_deleted: number; errors: string[] }> {
  const { data } = await apiClient.post<{ task_folders_scanned: number; dirs_deleted: number; errors: string[] }>('/execution/cleanup-output');
  return data;
}
