const API_BASE = ''

async function request(path, opts = {}) {
  const headers = { 'Content-Type': 'application/json', ...opts.headers }
  const res = await fetch(API_BASE + path, { ...opts, headers })
  return res
}

async function requestJSON(path, opts = {}) {
  const res = await request(path, opts)
  if (!res.ok) {
    let msg = `${res.status}`
    try {
      const body = await res.json()
      msg = body.detail || body.message || msg
    } catch {}
    const err = new Error(msg)
    err.status = res.status
    throw err
  }
  return res.json()
}

function apiFn(path, opts = {}) {
  return request(path, opts)
}

apiFn.get = (path) => requestJSON(path)
apiFn.post = (path, body) => requestJSON(path, { method: 'POST', body: JSON.stringify(body) })
apiFn.put = (path, body) => requestJSON(path, { method: 'PUT', body: JSON.stringify(body) })
apiFn.del = (path) => requestJSON(path, { method: 'DELETE' })

export const api = apiFn
