// ============================================
// 服务端 SQLite API 客户端
// ============================================

const API_BASE = import.meta.env.VITE_API_BASE || 'http://localhost:3001/api'

const requestJson = async (path, options = {}) => {
  const response = await fetch(`${API_BASE}${path}`, {
    headers: { 'Content-Type': 'application/json', ...(options.headers || {}) },
    ...options
  })

  if (!response.ok) {
    const errorText = await response.text()
    throw new Error(errorText || `请求失败: ${response.status}`)
  }

  const result = await response.json()
  if (result && result.success === false) {
    throw new Error(result.error || '请求失败')
  }

  return result?.data
}

export const initDatabase = async () => {
  await requestJson('/health')
  return true
}

export const saveToIndexedDB = async () => true

export const query = () => {
  throw new Error('服务端模式不支持直接 SQL 查询')
}

export const queryOne = () => {
  throw new Error('服务端模式不支持直接 SQL 查询')
}

export const execute = () => {
  throw new Error('服务端模式不支持直接 SQL 执行')
}

export const executeBatch = () => {
  throw new Error('服务端模式不支持直接 SQL 批量执行')
}

// ============================================
// 素材库 CRUD
// ============================================

export const getAllReferences = async () => {
  return requestJson('/references')
}

export const getReferenceById = async (id) => {
  return requestJson(`/references/${id}`)
}

export const getReferencesByType = async (type) => {
  return requestJson(`/references?type=${encodeURIComponent(type)}`)
}

export const addReference = async (reference) => {
  const data = await requestJson('/references', {
    method: 'POST',
    body: JSON.stringify(reference)
  })
  return data?.id
}

export const updateReference = async (id, updates) => {
  await requestJson(`/references/${id}`, {
    method: 'PUT',
    body: JSON.stringify(updates)
  })
  return true
}

export const deleteReference = async (id) => {
  await requestJson(`/references/${id}`, { method: 'DELETE' })
  return true
}

// ============================================
// 范式 CRUD
// ============================================

export const getAllParadigms = async () => {
  return requestJson('/paradigms')
}

export const getParadigmById = async (id) => {
  return requestJson(`/paradigms/${id}`)
}

export const addParadigm = async (paradigm) => {
  const data = await requestJson('/paradigms', {
    method: 'POST',
    body: JSON.stringify(paradigm)
  })
  return data?.id
}

export const updateParadigm = async (id, updates) => {
  await requestJson(`/paradigms/${id}`, {
    method: 'PUT',
    body: JSON.stringify(updates)
  })
  return true
}

export const deleteParadigm = async (id) => {
  await requestJson(`/paradigms/${id}`, { method: 'DELETE' })
  return true
}

// ============================================
// 用户配置 CRUD
// ============================================

export const getConfig = async (key, defaultValue = null) => {
  const data = await requestJson(`/config/${encodeURIComponent(key)}`)
  return data ?? defaultValue
}

export const setConfig = async (key, value) => {
  await requestJson(`/config/${encodeURIComponent(key)}`, {
    method: 'PUT',
    body: JSON.stringify({ value })
  })
  return true
}

// ============================================
// 文稿 CRUD
// ============================================

export const getAllDocuments = async () => {
  return requestJson('/documents')
}

export const getDocumentById = async (id) => {
  return requestJson(`/documents/${id}`)
}

export const getDocumentVersions = async (documentId) => {
  return requestJson(`/documents/${documentId}/versions`)
}

export const createDocument = async (document) => {
  const data = await requestJson('/documents', {
    method: 'POST',
    body: JSON.stringify(document)
  })
  return data?.id
}

export const updateDocument = async (id, updates) => {
  await requestJson(`/documents/${id}`, {
    method: 'PUT',
    body: JSON.stringify(updates)
  })
  return true
}

export const saveDocumentVersion = async (documentId, content, changeNote = '') => {
  const data = await requestJson(`/documents/${documentId}/versions`, {
    method: 'POST',
    body: JSON.stringify({ content, changeNote })
  })
  return data?.versionNumber
}

export const deleteDocument = async (id) => {
  await requestJson(`/documents/${id}`, { method: 'DELETE' })
  return true
}

export const clearDocuments = async () => {
  await requestJson('/documents/clear', { method: 'POST' })
  return true
}

export const getDocumentsByStatus = async (status) => {
  return requestJson(`/documents?status=${encodeURIComponent(status)}`)
}

// ============================================
// 数据导入/导出
// ============================================

export const exportDatabase = async () => {
  const response = await fetch(`${API_BASE}/db/export`)
  if (!response.ok) {
    const errorText = await response.text()
    throw new Error(errorText || '导出失败')
  }
  const buffer = await response.arrayBuffer()
  return new Uint8Array(buffer)
}

export const exportAsJSON = async () => {
  return requestJson('/db/export-json')
}

export const resetDatabase = async () => {
  await requestJson('/db/reset', { method: 'POST' })
  return true
}

// ============================================
// 提纲写作素材 CRUD
// ============================================

export const getAllOutlineMaterials = async () => {
  return requestJson('/outline-materials')
}

export const addOutlineMaterial = async (material) => {
  const data = await requestJson('/outline-materials', {
    method: 'POST',
    body: JSON.stringify(material)
  })
  return data?.id
}

export const updateOutlineMaterial = async (id, updates) => {
  await requestJson(`/outline-materials/${id}`, {
    method: 'PUT',
    body: JSON.stringify(updates)
  })
  return true
}

export const deleteOutlineMaterial = async (id) => {
  await requestJson(`/outline-materials/${id}`, { method: 'DELETE' })
  return true
}
