/**
 * 开发调试全链路日志 API。
 *
 * 对接后端 /api/admin/dev-trace/* 端点，提供日志查询、设置管理、
 * 覆盖率扫描、手动清理等功能。
 */

import { apiClient } from "./client";
import type {
  TraceFilter,
  TraceRequest,
  TraceDetail,
  TraceSettings,
  TraceCoverage,
} from "../types/devTrace";

// ---- 响应类型 ----

export interface TraceRequestListResponse {
  items: TraceRequest[];
  total: number;
  page: number;
  page_size: number;
}

export interface CleanupResponse {
  deleted_dates: string[];
  deleted_files: number;
}

// ---- 日期列表 ----

export async function fetchDates(): Promise<{ dates: string[] }> {
  const { data } = await apiClient.get<{ dates: string[] }>("/admin/dev-trace/dates");
  return data;
}

// ---- 请求列表（分页 + 筛选） ----

export async function fetchRequests(params: TraceFilter): Promise<TraceRequestListResponse> {
  const { data } = await apiClient.get<TraceRequestListResponse>("/admin/dev-trace/requests", { params });
  return data;
}

// ---- 请求详情（含完整 spans） ----

export async function fetchRequestDetail(requestId: string): Promise<TraceDetail> {
  const { data } = await apiClient.get<TraceDetail>(`/admin/dev-trace/request/${requestId}`);
  return data;
}

// ---- 手动清理 ----

export async function cleanupLogs(startDate: string, endDate: string): Promise<CleanupResponse> {
  const { data } = await apiClient.post<CleanupResponse>("/admin/dev-trace/cleanup", {
    start_date: startDate,
    end_date: endDate,
  });
  return data;
}

// ---- 设置 ----

export async function fetchSettings(): Promise<TraceSettings> {
  const { data } = await apiClient.get<TraceSettings>("/admin/dev-trace/settings");
  return data;
}

export async function updateSettings(settings: Partial<TraceSettings>): Promise<TraceSettings> {
  const { data } = await apiClient.put<TraceSettings>("/admin/dev-trace/settings", settings);
  return data;
}

// ---- 覆盖率 ----

export async function fetchCoverage(): Promise<TraceCoverage> {
  const { data } = await apiClient.get<TraceCoverage>("/admin/dev-trace/coverage");
  return data;
}

export async function triggerCoverageScan(): Promise<TraceCoverage> {
  const { data } = await apiClient.post<TraceCoverage>("/admin/dev-trace/coverage/scan");
  return data;
}
