const BASE = '/api'

function qs(query) {
  if (!query) return ''
  const p = new URLSearchParams()
  for (const [k, v] of Object.entries(query)) {
    if (v !== undefined && v !== null) p.set(k, v)
  }
  const s = p.toString()
  return s ? `?${s}` : ''
}

// Ein Request-Weg für ALLE Aufrufe (Creator-Muster): Backend-Fehler werfen mit
// err.status, damit Aufrufer 404/409 gesondert behandeln können.
async function req(path, { method = 'GET', body, query } = {}) {
  const opts = { method }
  if (body !== undefined) {
    opts.headers = { 'Content-Type': 'application/json' }
    opts.body = JSON.stringify(body)
  }
  const res = await fetch(`${BASE}${path}${qs(query)}`, opts)
  if (!res.ok) {
    let detail = `Fehler (HTTP ${res.status})`
    try {
      const data = await res.json()
      if (data.detail) detail = typeof data.detail === 'string' ? data.detail : JSON.stringify(data.detail)
    } catch { /* kein JSON-Body */ }
    const err = new Error(detail)
    err.status = res.status
    throw err
  }
  const text = await res.text()
  return text ? JSON.parse(text) : null
}

export const fetchProjekte = () => req('/projekte')
export const fetchOrdner = (pfad) => req('/fs', { query: { pfad } })
export const projektHinzufuegen = (pfad) =>
  req('/projekte', { method: 'POST', body: { pfad } })
export const projektEntfernen = (name) =>
  req(`/projekte/${encodeURIComponent(name)}`, { method: 'DELETE' })
export const fetchProjekt = (name) => req(`/projekte/${encodeURIComponent(name)}`)
export const fetchEinheit = (name, id) =>
  req(`/projekte/${encodeURIComponent(name)}/einheit`, { query: { id } })
export const starteScan = (name, art) =>
  req(`/projekte/${encodeURIComponent(name)}/scan`, { method: 'POST', body: { art } })
export const fetchScanStatus = (name) =>
  req(`/projekte/${encodeURIComponent(name)}/scan-status`)
