/**
 * 自动化部署测试模块 API 调用封装
 *
 * @author czj
 * @date 2026-08-12
 */

import request from '@/utils/request'
import type {
  DeployServer,
  DeployServerCreate,
  DeployServerUpdate,
  DeployServerListResponse,
  DeployScript,
  DeployScriptCreate,
  DeployScriptUpdate,
  DeployScriptListResponse,
  DeployExecution,
  DeployExecutionCreate,
  DeployExecutionListResponse,
  DeployLogListResponse,
  TestConnectionResponse,
  DeployMessage,
} from '@/types/deploy'

const BASE = '/api/deploy'

// ==================== 服务器 API ====================

/** 获取服务器列表 */
export function listServers(params?: {
  skip?: number
  limit?: number
  keyword?: string
}): Promise<DeployServerListResponse> {
  return request.get(`${BASE}/servers`, { params })
}

/** 获取服务器详情 */
export function getServer(id: string): Promise<DeployServer> {
  return request.get(`${BASE}/servers/${id}`)
}

/** 创建服务器 */
export function createServer(data: DeployServerCreate): Promise<DeployServer> {
  return request.post(`${BASE}/servers`, data)
}

/** 更新服务器 */
export function updateServer(id: string, data: DeployServerUpdate): Promise<DeployServer> {
  return request.put(`${BASE}/servers/${id}`, data)
}

/** 删除服务器 */
export function deleteServer(id: string): Promise<void> {
  return request.delete(`${BASE}/servers/${id}`)
}

/** 测试服务器连接 */
export function testServerConnection(id: string): Promise<TestConnectionResponse> {
  return request.post(`${BASE}/servers/${id}/test`)
}

// ==================== 脚本配置 API ====================

/** 获取脚本列表 */
export function listScripts(params?: {
  skip?: number
  limit?: number
  serverId?: string
  keyword?: string
}): Promise<DeployScriptListResponse> {
  return request.get(`${BASE}/scripts`, { params })
}

/** 获取脚本详情 */
export function getScript(id: string): Promise<DeployScript> {
  return request.get(`${BASE}/scripts/${id}`)
}

/** 创建脚本配置 */
export function createScript(data: DeployScriptCreate): Promise<DeployScript> {
  return request.post(`${BASE}/scripts`, data)
}

/** 更新脚本配置 */
export function updateScript(id: string, data: DeployScriptUpdate): Promise<DeployScript> {
  return request.put(`${BASE}/scripts/${id}`, data)
}

/** 删除脚本配置 */
export function deleteScript(id: string): Promise<void> {
  return request.delete(`${BASE}/scripts/${id}`)
}

// ==================== 执行记录 API ====================

/** 获取执行记录列表 */
export function listExecutions(params?: {
  skip?: number
  limit?: number
  scriptId?: string
  status?: string
}): Promise<DeployExecutionListResponse> {
  return request.get(`${BASE}/executions`, { params })
}

/** 获取执行记录详情 */
export function getExecution(id: string): Promise<DeployExecution> {
  return request.get(`${BASE}/executions/${id}`)
}

/** 创建执行记录 */
export function createExecution(data: DeployExecutionCreate): Promise<DeployExecution> {
  return request.post(`${BASE}/executions`, data)
}

/** 开始执行部署（POST，等待执行完成） */
export function runExecution(id: string): Promise<DeployExecution> {
  return request.post(`${BASE}/executions/${id}/run`)
}

/** 取消执行 */
export function cancelExecution(id: string): Promise<DeployExecution> {
  return request.post(`${BASE}/executions/${id}/cancel`)
}

/** 删除执行记录 */
export function deleteExecution(id: string): Promise<void> {
  return request.delete(`${BASE}/executions/${id}`)
}

/** 获取执行日志 */
export function listExecutionLogs(id: string, params?: {
  skip?: number
  limit?: number
}): Promise<DeployLogListResponse> {
  return request.get(`${BASE}/executions/${id}/logs`, { params })
}

// ==================== WebSocket 实时日志 ====================

/** 创建 WebSocket 连接订阅部署实时日志 */
export function createDeployLogStream(
  executionId: string,
  onMessage: (msg: DeployMessage) => 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/deploy/ws/executions/${executionId}`)

  ws.onmessage = (event) => {
    try {
      const msg = JSON.parse(event.data) as DeployMessage
      onMessage(msg)
    } catch (e) {
      console.error('解析 WebSocket 消息失败', e)
    }
  }

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

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

  return ws
}