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

import request from '@/utils/request'
import type {
  PerformanceTask,
  PerformanceTaskCreate,
  PerformanceTaskUpdate,
  PerformanceTaskListResponse,
  PerformanceRunRequest,
  PerformanceRunResponse,
  PerformanceSnapshotListResponse,
  PerformanceReportResponse,
} 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
}