/**
 * 服务管理模块 API
 *
 * 包含服务授权与目标配置的接口调用。
 */

import http from '@/utils/http'
import type {
  ManageTarget,
  CreateManageTargetRequest,
  UpdateManageTargetRequest,
  TestManageTargetRequest,
  TestManageTargetResponse,
  LicenseTaskStatus,
  UploadLicenseResponse,
  ProjectInfo,
  SaveProjectRequest,
  UploadFileResult,
} from '@/types/service-manage'

// ============================================================
// 目标配置
// ============================================================

/** 目标列表 */
export async function getTargets(): Promise<{ success: boolean; targets: ManageTarget[] }> {
  const res = await http.get<{ success: boolean; targets: ManageTarget[] }>('/api/service-manage/targets')
  return res.data
}

/** 新增目标 */
export async function createTarget(data: CreateManageTargetRequest): Promise<{ success: boolean; target: ManageTarget }> {
  const res = await http.post<{ success: boolean; target: ManageTarget }>('/api/service-manage/targets', data)
  return res.data
}

/** 更新目标 */
export async function updateTarget(
  targetId: string,
  data: UpdateManageTargetRequest
): Promise<{ success: boolean; target: ManageTarget }> {
  const res = await http.put<{ success: boolean; target: ManageTarget }>(
    `/api/service-manage/targets/${targetId}`,
    data
  )
  return res.data
}

/** 删除目标 */
export async function deleteTarget(targetId: string): Promise<{ success: boolean }> {
  const res = await http.delete<{ success: boolean }>(`/api/service-manage/targets/${targetId}`)
  return res.data
}

/** 测试连接 */
export async function testConnection(data: TestManageTargetRequest): Promise<TestManageTargetResponse> {
  const res = await http.post<TestManageTargetResponse>('/api/service-manage/targets/test', data)
  return res.data
}

// ============================================================
// 服务授权
// ============================================================

/** 下载激活文件（Blob） */
export async function downloadLicense(): Promise<Blob> {
  const res = await http.get<Blob>('/api/service-manage/license/download', { responseType: 'blob' })
  return res.data
}

/** 上传授权文件 */
export async function uploadLicense(file: File): Promise<UploadLicenseResponse> {
  const formData = new FormData()
  formData.append('file', file)
  const res = await http.post<UploadLicenseResponse>('/api/service-manage/license/upload', formData, {
    headers: { 'Content-Type': 'multipart/form-data' },
  })
  return res.data
}

/** 查询授权任务状态 */
export async function getLicenseTaskStatus(taskId: string): Promise<LicenseTaskStatus> {
  const res = await http.get<LicenseTaskStatus>('/api/service-manage/license/task-status', {
    params: { taskId },
  })
  return res.data
}

/** 读取项目信息 */
export async function getProject(): Promise<{ success: boolean; project: ProjectInfo | null }> {
  const res = await http.get<{ success: boolean; project: ProjectInfo | null }>('/api/service-manage/project')
  return res.data
}

/** 保存项目信息 */
export async function saveProject(data: SaveProjectRequest): Promise<{ success: boolean; message: string }> {
  const res = await http.post<{ success: boolean; message: string }>('/api/service-manage/project', data)
  return res.data
}

/** 下载部署视图（Blob） */
export async function downloadDeployView(): Promise<Blob> {
  const res = await http.get<Blob>('/api/service-manage/deploy-view/download', { responseType: 'blob' })
  return res.data
}

/** 上传部署视图 */
export async function uploadDeployView(file: File): Promise<UploadFileResult> {
  const formData = new FormData()
  formData.append('file', file)
  const res = await http.post<UploadFileResult>('/api/service-manage/deploy-view/upload', formData, {
    headers: { 'Content-Type': 'multipart/form-data' },
  })
  return res.data
}

/** 下载自检文档（Blob） */
export async function downloadSelfCheck(): Promise<Blob> {
  const res = await http.get<Blob>('/api/service-manage/self-check/download', { responseType: 'blob' })
  return res.data
}

/** 上传自检文档 */
export async function uploadSelfCheck(file: File): Promise<UploadFileResult> {
  const formData = new FormData()
  formData.append('file', file)
  const res = await http.post<UploadFileResult>('/api/service-manage/self-check/upload', formData, {
    headers: { 'Content-Type': 'multipart/form-data' },
  })
  return res.data
}

// ============================================================
// 工具：Blob 下载
// ============================================================

/** 触发浏览器下载 Blob */
export function downloadBlob(blob: Blob, filename: string) {
  const url = URL.createObjectURL(blob)
  const link = document.createElement('a')
  link.href = url
  link.download = filename
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
  URL.revokeObjectURL(url)
}