/**
 * Extract a human-readable Chinese error message from anything caught in a try/catch.
 * Prefers meaningful messages from API responses; falls back to the provided default.
 */
export function getErrorMessage(err: unknown, fallback = "操作失败"): string {
  if (err instanceof Error) return err.message || fallback
  if (typeof err === "string") return err
  return fallback
}

/**
 * Try to pull an error message from an API response body of unknown shape.
 * Handles:
 *   - { code, message }        (ApiResult / custom backend wrapper)
 *   - { error, message }       (Spring Boot default error attributes)
 *   - { message }              (plain message)
 *   - string body
 */
export function extractMessageFromBody(body: unknown): string | null {
  if (!body) return null
  if (typeof body === "string") return body
  if (typeof body !== "object") return null

  const d = body as Record<string, unknown>

  // Preferred: message field (ApiResult and Spring Boot both use this)
  if (typeof d.message === "string" && d.message) return d.message

  // Spring Boot sometimes puts the summary in "error" and detail in "message"
  if (typeof d.error === "string" && d.error) return d.error

  return null
}
