// 鉴权：每个请求加 Authorization: token <pass>，<audio> 用 ?token= 兜底。

const KEY = 'notes.pass'

export function getPass() {
  return localStorage.getItem(KEY) || ''
}
export function setPass(v) {
  localStorage.setItem(KEY, v || '')
}
export function clearPass() {
  localStorage.removeItem(KEY)
}

async function jreq(path, opts = {}) {
  const pass = getPass()
  const h = { 'Authorization': 'token ' + pass, ...(opts.headers || {}) }
  if (opts.body && !(opts.body instanceof FormData) && !h['Content-Type']) {
    h['Content-Type'] = 'application/json'
  }
  const r = await fetch(path, { ...opts, headers: h })
  if (r.status === 401) {
    const err = new Error('unauthorized')
    err.unauthorized = true
    throw err
  }
  if (!r.ok) {
    const t = await r.text().catch(() => '')
    throw new Error(t || `${r.status}`)
  }
  return r.json()
}

export function listRecordings() { return jreq('/api/recordings') }
export function getRecording(id) { return jreq('/api/recordings/' + id) }
export function deleteRecording(id) { return jreq('/api/recordings/' + id, { method: 'DELETE' }) }
export function renameRecording(id, title) {
  return jreq('/api/recordings/' + id, { method: 'PATCH', body: JSON.stringify({ title }) })
}
export function retryRecording(id) { return jreq('/api/recordings/' + id + '/retry', { method: 'POST' }) }
export function convertFeishu(id) {
  return jreq('/api/recordings/' + id + '/feishu', { method: 'POST' })
}

export function uploadRecording(title, file) {
  const fd = new FormData()
  if (title) fd.append('title', title)
  fd.append('audio', file, file.name)
  return jreq('/api/recordings', { method: 'POST', body: fd })
}

export function audioUrl(id) {
  return `/api/recordings/${id}/audio?token=${encodeURIComponent(getPass())}`
}
