/**
 * Normalise errors coming out of the axios-backed API client into a
 * user-facing string. FastAPI puts validation/permission errors on
 * `response.data.detail`; network timeouts / CORS surface as the axios
 * `message`. Engine messages like "SyntaxError" or bare "Network Error"
 * are filtered out in favour of a stable fallback so users never see
 * raw parser noise in a toast.
 */
export function formatApiError(err: unknown, fallback = 'Something went wrong'): string {
  if (!err) return fallback

  const anyErr = err as {
    response?: { data?: { detail?: unknown; error?: unknown; message?: unknown } }
    message?: string
  }

  const fromDetail = anyErr.response?.data?.detail
  if (typeof fromDetail === 'string' && fromDetail.trim()) return fromDetail
  // FastAPI validation errors come through as an array of objects.
  if (Array.isArray(fromDetail) && fromDetail.length > 0) {
    const first = fromDetail[0] as { msg?: string }
    if (first?.msg) return first.msg
  }

  const fromError = anyErr.response?.data?.error
  if (typeof fromError === 'string' && fromError.trim()) return fromError

  const fromMessage = anyErr.response?.data?.message
  if (typeof fromMessage === 'string' && fromMessage.trim()) return fromMessage

  // Axios "Network Error" and native runtime errors like SyntaxError are
  // worse than a stable fallback — filter them out.
  const msg = anyErr.message
  if (typeof msg === 'string' && msg.trim() && msg !== 'Network Error') {
    return msg
  }
  return fallback
}
