const BASE = '/api'

async function request(path, opts = {}) {
  const res = await fetch(`${BASE}${path}`, {
    headers: { 'Content-Type': 'application/json', ...(opts.headers ?? {}) },
    ...opts,
  })
  if (!res.ok) {
    const body = await res.text().catch(() => '')
    throw new Error(`API ${res.status} ${res.statusText}${body ? `: ${body}` : ''}`)
  }
  return res.status === 204 ? null : res.json()
}

export const schemaApi = {
  list: () => request('/task-schemas'),
  get: (id) => request(`/task-schemas/${id}`),
  create: (data) => request('/task-schemas', { method: 'POST', body: JSON.stringify(data) }),
  update: (id, data) => request(`/task-schemas/${id}`, { method: 'PUT', body: JSON.stringify(data) }),
  remove: (id) => request(`/task-schemas/${id}`, { method: 'DELETE' }),
}

export const taskApi = {
  list: (filter) => request(`/tasks${filter ? `?filter=${filter}` : ''}`),
  get: (id) => request(`/tasks/${id}`),
  update: (id, data) => request(`/tasks/${id}`, { method: 'PUT', body: JSON.stringify(data) }),
  remove: (id) => request(`/tasks/${id}`, { method: 'DELETE' }),
  toggle: (id) => request(`/tasks/${id}/toggle`, { method: 'PATCH' }),
  statuses: () => request('/tasks/statuses'),
}
