/**
 * 性能测试模块 API 调用封装
 *
 * @author czj
 * @date 2026-08-12
 */

import request from '@/utils/request'
import type {
  PerformanceTask,
  PerformanceTaskCreate,
  PerformanceTaskUpdate,
  PerformanceTaskListResponse,
  PerformanceRunRequest,
  PerformanceRunResponse,
  PerformanceSnapshotListResponse,
  PerformanceReportResponse,
  CurlParseResult,
} from '@/types/performance'

const BASE = '/api/performance'

// ==================== 任务 CRUD ====================

/** 获取任务列表 */
export function listTasks(params?: {
  page?: number
  pageSize?: number
  status?: string
}): Promise<PerformanceTaskListResponse> {
  return request.get(`${BASE}/tasks`, { params })
}

/** 获取任务详情 */
export function getTask(id: string): Promise<PerformanceTask> {
  return request.get(`${BASE}/tasks/${id}`)
}

/** 创建任务 */
export function createTask(data: PerformanceTaskCreate): Promise<PerformanceTask> {
  return request.post(`${BASE}/tasks`, data)
}

/** 更新任务 */
export function updateTask(id: string, data: PerformanceTaskUpdate): Promise<PerformanceTask> {
  return request.put(`${BASE}/tasks/${id}`, data)
}

/** 删除任务 */
export function deleteTask(id: string): Promise<void> {
  return request.delete(`${BASE}/tasks/${id}`)
}

// ==================== 执行控制 ====================

/** 执行任务 */
export function runTask(id: string, data?: PerformanceRunRequest): Promise<PerformanceRunResponse> {
  return request.post(`${BASE}/tasks/${id}/run`, data || {})
}

/** 停止任务 */
export function stopTask(id: string): Promise<PerformanceRunResponse> {
  return request.post(`${BASE}/tasks/${id}/stop`)
}

// ==================== 快照与报告 ====================

/** 获取快照数据 */
export function getSnapshots(id: string, params?: {
  page?: number
  pageSize?: number
}): Promise<PerformanceSnapshotListResponse> {
  return request.get(`${BASE}/tasks/${id}/snapshots`, { params })
}

/** 获取报告 */
export function getReport(id: string): Promise<PerformanceReportResponse> {
  return request.get(`${BASE}/tasks/${id}/report`)
}

/** 获取任务执行结果 */
export function getTaskResults(id: string): Promise<PerformanceTask> {
  return request.get(`${BASE}/tasks/${id}/results`)
}

// ==================== WebSocket 实时监控 ====================

/** 创建 WebSocket 连接订阅性能测试实时数据 */
export function createPerfMonitorStream(
  taskId: string,
  onSnapshot: (data: any) => void,
  onComplete: (data: any) => void,
  onError?: (error: Event) => void,
  onClose?: () => void,
): WebSocket {
  const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:'
  const host = window.location.host
  const ws = new WebSocket(`${protocol}//${host}/api/performance/ws/${taskId}`)

  ws.onmessage = (event) => {
    try {
      const msg = JSON.parse(event.data)
      if (msg.type === 'perf_snapshot') {
        onSnapshot(msg)
      } else if (msg.type === 'perf_complete') {
        onComplete(msg)
      }
    } catch (e) {
      console.error('解析 WebSocket 消息失败', e)
    }
  }

  ws.onerror = (error) => {
    console.error('WebSocket 错误', error)
    onError?.(error)
  }

  ws.onclose = () => {
    onClose?.()
  }

  return ws
}

// ==================== API 接口预设 ====================

/** 获取预设列表 */
export function listPresets(params?: {
  page?: number
  pageSize?: number
  keyword?: string
}): Promise<any> {
  return request.get(`${BASE}/presets`, { params })
}

/** 获取预设详情 */
export function getPreset(id: string): Promise<any> {
  return request.get(`${BASE}/presets/${id}`)
}

/** 创建预设 */
export function createPreset(data: any): Promise<any> {
  return request.post(`${BASE}/presets`, data)
}

/** 更新预设 */
export function updatePreset(id: string, data: any): Promise<any> {
  return request.put(`${BASE}/presets/${id}`, data)
}

/** 删除预设 */
export function deletePreset(id: string): Promise<void> {
  return request.delete(`${BASE}/presets/${id}`)
}

// ==================== curl 解析 ====================

/** 解析 curl 命令，返回结构化压测配置 */
export function parseCurl(curlCommand: string): Promise<CurlParseResult> {
  return request.post(`${BASE}/parse-curl`, { curlCommand })
}