import { ApiError } from '@/api'

/** Turn FastAPI error bodies into a human-readable string. */
export function formatApiError(e: unknown, fallback: string): string {
  if (e instanceof ApiError) {
    const d = (e as ApiError & { detail?: unknown }).detail ?? e.message
    if (typeof d === 'string') return d
    if (Array.isArray(d)) {
      return d.map((x: { msg?: string }) => x?.msg || JSON.stringify(x)).join('; ')
    }
    if (d && typeof d === 'object') return JSON.stringify(d)
    return e.message || fallback
  }
  if (e instanceof Error) return e.message || fallback
  return fallback
}
