import api from '@/api'

export function downloadJSON(filename, data) {
  const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' })
  const url = URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.href = url
  a.download = filename
  a.click()
  URL.revokeObjectURL(url)
}

export function parseImportFile(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.onload = () => {
      try {
        const data = JSON.parse(reader.result)
        const items = Array.isArray(data) ? data : data?.items
        if (!Array.isArray(items) || items.length === 0) {
          reject(new Error('文件中没有可导入的配置项'))
          return
        }
        resolve(items)
      } catch {
        reject(new Error('JSON 格式无效'))
      }
    }
    reader.onerror = () => reject(new Error('读取文件失败'))
    reader.readAsText(file)
  })
}

export async function exportResource(path, filename) {
  const { data } = await api.get(`${path}/export`)
  downloadJSON(filename, data)
  return data
}

export async function importResource(path, mode, items) {
  const { data } = await api.post(`${path}/import`, { mode, items })
  return data
}

export function importModeLabel(mode) {
  const map = {
    upsert: '覆盖更新（已存在则更新）',
    skip: '跳过已存在（仅导入新配置）',
    create: '全部新建（冲突则跳过）',
  }
  return map[mode] || mode
}
