/**
 * 队列任务监控大屏 API
 */
import { requestClient } from '#/api/request';

const prefix = 'queue-job/';

export type QueueJobMonitorSummary = {
  total: number;
  pending: number;
  pending_total: number;
  delayed: number;
  running: number;
  success: number;
  failed: number;
  cancelled: number;
  fail_rate: number | null;
};

export type QueueJobMonitorTrendItem = {
  label: string;
  start_at: number;
  created: number;
  success: number;
  failed: number;
};

export type QueueJobMonitorResult = {
  now: number;
  hours: number;
  summary: QueueJobMonitorSummary;
  by_category: Array<{
    category: number;
    category_txt: string;
    total: number;
    pending: number;
    running: number;
    success: number;
    failed: number;
  }>;
  trend: QueueJobMonitorTrendItem[];
  top_failed_jobs: Array<{
    job_name: string;
    label: string;
    count: number;
  }>;
  recent_failures: Array<{
    id: number;
    title: string;
    job_name: string;
    job_name_txt: string;
    category: number;
    category_txt: string;
    error_message: string;
    updated_at: string | number;
    created_at: string | number;
  }>;
};

/**
 * 拉取监控统计；hours 为趋势窗口（默认 24）
 */
export async function getQueueJobStats(hours = 24) {
  return requestClient.get<QueueJobMonitorResult>(`${prefix}stats`, {
    params: { hours },
  });
}

export type QueueJobProbeResult = {
  normal_id: number;
  delayed_id: number;
  fail_id: number;
  delay_seconds: number;
  available_at: number;
};

/**
 * 超管测试探针：普通 / 延迟 / 失败 各投一条
 */
export async function createQueueJobProbe(data: {
  delay_amount: number;
  delay_unit: 'second' | 'minute' | 'hour' | 'day';
}) {
  return requestClient.post<QueueJobProbeResult>(`${prefix}create-probe`, data);
}
