export class ApiError extends Error {
  constructor(message, { status = 0, payload = null } = {}) {
    super(message)
    this.name = 'ApiError'
    this.status = status
    this.payload = payload
  }
}

export async function request(path, {
  signal,
  method = 'GET',
  body,
  json,
  headers = {},
} = {}) {
  const finalHeaders = { ...headers }
  let finalBody = body
  if (json !== undefined) {
    finalHeaders['Content-Type'] = finalHeaders['Content-Type'] || 'application/json'
    finalBody = JSON.stringify(json)
  }
  const response = await fetch(path, {
    signal,
    method,
    headers: finalHeaders,
    body: finalBody,
  })
  const contentType = response.headers.get('content-type') || ''
  const payload = contentType.includes('application/json')
    ? await response.json().catch(() => null)
    : await response.text().catch(() => '')
  if (!response.ok) {
    const message = payload?.detail || payload?.message || `请求失败：${response.status}`
    throw new ApiError(message, { status: response.status, payload })
  }
  return payload
}
