const BASE = '/api'

export async function apiFetch(path, options = {}) {
  const res = await fetch(`${BASE}${path}`, {
    headers: { 'Content-Type': 'application/json', ...options.headers },
    ...options,
  })
  if (!res.ok) {
    const text = await res.text().catch(() => res.statusText)
    throw new Error(text || res.statusText)
  }
  return res.json()
}

export const getStats  = ()           => apiFetch('/stats')
export const getTests  = (params = {}) => {
  const qs = new URLSearchParams(
    Object.entries(params).filter(([, v]) => v !== '' && v !== undefined && v !== null)
  ).toString()
  return apiFetch(`/tests${qs ? `?${qs}` : ''}`)
}
export const getConfig = ()           => apiFetch('/config')
export const saveConfig = (body)      => apiFetch('/config', { method: 'POST', body: JSON.stringify(body) })
export const browse    = (path)       => apiFetch(`/browse${path ? `?path=${encodeURIComponent(path)}` : ''}`)
