export type AnalyticsErrorContext = {
  action?: string
  fallbackMessage?: string
}

export function mapAnalyticsError(err: any, ctx?: AnalyticsErrorContext): string {
  const fallback = ctx?.fallbackMessage ?? '操作失败'

  try {
    if (err == null) return fallback

    // string
    if (typeof err === 'string') {
      const s = err.trim()
      return s.length > 0 ? s : fallback
    }

    // Error
    const eAny = err as any
    const msg: string = (eAny?.message != null ? String(eAny.message) : '')
    const code: string = (eAny?.code != null ? String(eAny.code) : '')
    const status: number | null = (typeof eAny?.status === 'number' ? (eAny.status as number) : null)

    // RPC not found / route not found
    if (status === 404) {
      return '功能尚未部署（RPC 未创建）'
    }

    // auth
    if (code === 'P0001' || msg.includes('用户未登录') || msg.toLowerCase().includes('not logged') || msg.toLowerCase().includes('jwt')) {
      return '请先登录'
    }

    // permission
    if (msg.includes('无权限') || msg.toLowerCase().includes('permission') || msg.toLowerCase().includes('forbidden')) {
      return '无权限操作'
    }

    // not found
    if (msg.includes('不存在') || msg.toLowerCase().includes('not found')) {
      return '数据不存在或已删除'
    }

    // fallback to message
    if (msg.trim().length > 0) {
      return msg
    }

    return fallback
  } catch (e) {
    return fallback
  }
}
