/**
 * 服务监测 - 报告管理 API
 */
import http from '@/utils/http'
import { createSSE } from '@/utils/sse'
import type {
  ReportSummary,
  ReportDetail,
  BatchDeleteReportsRequest,
  RunStatusResponse,
  InspectProgressEvent,
  CompareResult,
} from '@/types/service-monitor'

/** 获取报告列表 */
export async function getReports(
  params?: { target_id?: string }
): Promise<{ success: boolean; reports: ReportSummary[] }> {
  const res = await http.get<{ success: boolean; reports: ReportSummary[] }>(
    '/api/service-monitor/reports',
    { params }
  )
  return res.data
}

/** 获取报告详情 */
export async function getReport(reportId: string): Promise<{ success: boolean; report: ReportDetail }> {
  const res = await http.get<{ success: boolean; report: ReportDetail }>(
    `/api/service-monitor/reports/${reportId}`
  )
  return res.data
}

/** 删除报告 */
export async function deleteReport(reportId: string): Promise<{ success: boolean }> {
  const res = await http.delete<{ success: boolean }>(`/api/service-monitor/reports/${reportId}`)
  return res.data
}

/** 批量删除报告 */
export async function batchDeleteReports(
  data: BatchDeleteReportsRequest
): Promise<{ success: boolean; deleted: number }> {
  const res = await http.delete<{ success: boolean; deleted: number }>(
    '/api/service-monitor/reports/batch',
    { data }
  )
  return res.data
}

/** 导出报告 */
export function getReportExportUrl(
  reportId: string,
  format: 'md' | 'json' | 'excel' | 'pdf' = 'md',
  token?: string
): string {
  let url = `/api/service-monitor/reports/${reportId}/export?format=${format}`
  if (token) {
    url += `&token=${token}`
  }
  return url
}

/** 对比报告 */
export async function compareReports(
  reportIdA: string,
  reportIdB: string
): Promise<{ success: boolean; data: CompareResult }> {
  const res = await http.get<{ success: boolean; data: CompareResult }>(
    `/api/service-monitor/reports/${reportIdA}/compare/${reportIdB}`
  )
  return res.data
}

/** 导出对比报告 URL */
export function getCompareExportUrl(
  reportIdA: string,
  reportIdB: string,
  format: 'md' | 'html' = 'md'
): string {
  return `/api/service-monitor/reports/${reportIdA}/compare/${reportIdB}/export?format=${format}`
}

/** 查询巡检运行状态 */
export async function getRunStatus(targetId: string): Promise<RunStatusResponse> {
  const res = await http.get<RunStatusResponse>(
    `/api/service-monitor/run/status/${targetId}`
  )
  return res.data
}

/** 取消巡检 */
export async function cancelRun(runId: string): Promise<{ success: boolean }> {
  const res = await http.post<{ success: boolean }>(
    `/api/service-monitor/run/${runId}/cancel`
  )
  return res.data
}

/** 流式巡检（SSE） */
export function runInspection(
  targetId: string,
  suite: 'quick' | 'full' = 'quick',
  handlers: Record<string, (data: InspectProgressEvent) => void>,
  onError?: (error: Event) => void
) {
  return createSSE({
    url: '/api/service-monitor/run/stream',
    params: { target_id: targetId, suite },
    handlers,
    onError,
  })
}