/** Format FastAPI 422 validation detail items for display (Chinese). */

const LOC_PREFIX_SKIP = new Set(['body', 'query', 'path', 'header', 'cookie'])

export function formatValidationDetailItem(x: {
  msg?: string
  loc?: unknown[]
  loc_zh?: string
}): string {
  const part = (x?.msg || '').trim()
  if (x?.loc_zh) {
    return part ? `${x.loc_zh}：${part}` : x.loc_zh
  }
  const loc = Array.isArray(x?.loc)
    ? x.loc.filter((p) => !LOC_PREFIX_SKIP.has(String(p)))
    : []
  const locStr = loc
    .map((p) => (typeof p === 'number' ? `第${p + 1}项` : String(p)))
    .join('.')
  if (locStr && part) return `${locStr}：${part}`
  return part || locStr || JSON.stringify(x)
}

export function formatValidationDetail(detail: unknown, fallback: string): string {
  if (typeof detail === 'string') {
    const s = detail.trim()
    return s || fallback
  }
  if (Array.isArray(detail)) {
    const msg = detail.map((x) => formatValidationDetailItem(x as { msg?: string; loc?: unknown[]; loc_zh?: string })).join('；')
    return msg.trim() || fallback
  }
  if (detail && typeof detail === 'object') {
    return JSON.stringify(detail)
  }
  return fallback
}
