const BASE = '/api'

async function request(path, options = {}) {
  const res = await fetch(`${BASE}${path}`, {
    headers: { 'Content-Type': 'application/json', ...options.headers },
    ...options,
  })
  if (!res.ok) {
    const err = await res.json().catch(() => ({ message: res.statusText }))
    throw new Error(err.message || 'Request failed')
  }
  if (res.status === 204) return null
  return res.json()
}

// ── Authors ──────────────────────────────────────────────────────────────
export const authorsApi = {
  getAll:        (params = {}) => request('/authors?' + new URLSearchParams(params)),
  getById:       (id)          => request(`/authors/${id}`),
  create:        (body)        => request('/authors',     { method: 'POST', body: JSON.stringify(body) }),
  update:        (id, body)    => request(`/authors/${id}`, { method: 'PUT',  body: JSON.stringify(body) }),
  delete:        (id)          => request(`/authors/${id}`, { method: 'DELETE' }),
  topBorrowed:   (topN = 5)    => request(`/authors/top-borrowed?topN=${topN}`),
}

// ── Books ────────────────────────────────────────────────────────────────
export const booksApi = {
  getAll:  (params = {}) => request('/books?' + new URLSearchParams(
    Object.fromEntries(Object.entries(params).filter(([, v]) => v !== '' && v != null))
  )),
  getById: (id)       => request(`/books/${id}`),
  create:  (body)     => request('/books',     { method: 'POST', body: JSON.stringify(body) }),
  update:  (id, body) => request(`/books/${id}`, { method: 'PUT',  body: JSON.stringify(body) }),
  delete:  (id)       => request(`/books/${id}`, { method: 'DELETE' }),
}

// ── Borrow Records ────────────────────────────────────────────────────────
export const borrowApi = {
  getAll:        (params = {}) => request('/borrowrecords?' + new URLSearchParams(
    Object.fromEntries(Object.entries(params).filter(([, v]) => v !== '' && v != null))
  )),
  getById:       (id)          => request(`/borrowrecords/${id}`),
  create:        (body)        => request('/borrowrecords',      { method: 'POST', body: JSON.stringify(body) }),
  update:        (id, body)    => request(`/borrowrecords/${id}`, { method: 'PUT',  body: JSON.stringify(body) }),
  delete:        (id)          => request(`/borrowrecords/${id}`, { method: 'DELETE' }),
  overdueReport: ()            => request('/borrowrecords/overdue-report'),
}
