/**
 * 调度任务相关 API 调用。
 */

import { apiClient } from './client';
import type { ScheduledTask, ScheduleConfig, TaskConfig, ExecutionLog, MinRunIntervalItem } from '../types';

/** 获取调度任务列表 */
export async function fetchSchedules(): Promise<ScheduledTask[]> {
  const { data } = await apiClient.get<ScheduledTask[]>('/schedules');
  return data;
}

/** 创建调度任务 */
export async function createSchedule(payload: {
  name: string;
  task_codes: string[];
  task_config: TaskConfig;
  schedule_config: ScheduleConfig;
  run_immediately?: boolean;
  min_run_interval_value?: number;
  min_run_interval_unit?: string;
  min_run_intervals?: Record<string, MinRunIntervalItem>;
}): Promise<ScheduledTask> {
  const { data } = await apiClient.post<ScheduledTask>('/schedules', payload);
  return data;
}

/** 更新调度任务 */
export async function updateSchedule(
  id: string,
  payload: Partial<{
    name: string;
    task_codes: string[];
    task_config: TaskConfig;
    schedule_config: ScheduleConfig;
    min_run_interval_value: number;
    min_run_interval_unit: string;
    min_run_intervals: Record<string, MinRunIntervalItem>;
  }>,
): Promise<ScheduledTask> {
  const { data } = await apiClient.put<ScheduledTask>(`/schedules/${id}`, payload);
  return data;
}

/** 删除调度任务 */
export async function deleteSchedule(id: string): Promise<void> {
  await apiClient.delete(`/schedules/${id}`);
}

/** 启用/禁用调度任务 */
export async function toggleSchedule(id: string): Promise<ScheduledTask> {
  const { data } = await apiClient.patch<ScheduledTask>(`/schedules/${id}/toggle`);
  return data;
}

/** 手动执行调度任务一次（不更新调度间隔） */
export async function runScheduleNow(id: string, force = false): Promise<{ message: string; task_id: string }> {
  const { data } = await apiClient.post<{ message: string; task_id: string }>(`/schedules/${id}/run`, null, {
    params: force ? { force: true } : undefined,
  });
  return data;
}

/** 获取调度任务的执行历史 */
export async function fetchScheduleHistory(
  id: string,
  page = 1,
  pageSize = 50,
): Promise<ExecutionLog[]> {
  const { data } = await apiClient.get<ExecutionLog[]>(`/schedules/${id}/history`, {
    params: { page, page_size: pageSize },
  });
  return data;
}
