/**
 * 文档操作 API 模块
 * 封装文档详情获取、知识图谱、版本列表、原文下载、文档删除等接口。
 */
import request from './request'
import type { DocumentDetail, RelatedDoc, VersionListResponse } from '@/types/document'
import type { GraphData } from '@/types/graph'

/**
 * Get full document detail by ID
 */
/** 根据文档 ID 获取完整详情（元数据 + 摘要等） */
export function getDocumentDetail(docId: string): Promise<DocumentDetail> {
  return request
    .get<DocumentDetail>(`/api/ai/v1/document/${docId}`)
    .then((res) => res.data)
}

/**
 * Get the knowledge graph for a specific document
 */
/** 获取指定文档的知识图谱数据（节点 + 边） */
export function getDocumentGraph(docId: string): Promise<GraphData> {
  return request
    .get<GraphData>(`/api/ai/v1/document/${docId}/graph`)
    .then((res) => res.data)
}

/**
 * List all document versions sharing the same content_hash
 */
/** 根据 content_hash 查询同内容的所有版本文档 */
export function getDocumentVersions(contentHash: string): Promise<VersionListResponse> {
  return request
    .get<VersionListResponse>(`/api/ai/v1/document/versions/${contentHash}`)
    .then((res) => res.data)
}

/**
 * Download the original file for a document.
 * Uses axios to send the JWT token in the Authorization header,
 * then creates a blob URL for the browser to download.
 */
/** 下载文档原文件；通过 Blob URL 触发浏览器下载 */
export async function downloadDocumentFile(docId: string, filename?: string): Promise<void> {
  const res = await request.get(`/api/ai/v1/document/file/${docId}`, {
    responseType: 'blob',
  })
  const contentType = res.headers['content-type'] || 'application/octet-stream'
  const blob = new Blob([res.data], { type: contentType })
  const url = window.URL.createObjectURL(blob)
  const link = window.document.createElement('a')
  link.href = url
  link.download = filename || `${docId}`
  link.click()
  window.URL.revokeObjectURL(url)
}

/**
 * Delete a document by ID
 */
/** 根据 ID 删除文档 */
export function deleteDocument(docId: string): Promise<any> {
  return request
    .delete(`/api/ai/v1/document/${docId}`)
    .then((res) => res.data)
}

/** 更新文档关联文件列表（双向绑定） */
export function updateRelatedDocs(docId: string, relatedDocs: RelatedDoc[]): Promise<any> {
  return request
    .put(`/api/ai/v1/document/${docId}/related-docs`, { related_docs: relatedDocs })
    .then((res) => res.data)
}
