import { useMessage } from 'naive-ui'

/** 前端错误消息翻译映射（覆盖后端返回的英文消息，与 backend/app/core/i18n.py 保持同步） */
const FRONTEND_ERRORS: Record<string, string> = {
  'Invalid credentials': '邮箱或密码错误',
  'Account disabled': '账号已停用',
  'Invalid or expired token': '登录已过期，请重新登录',
  'Refresh token revoked': '刷新令牌已被吊销',
  'String should have at least 8 characters': '密码长度不能少于8位',
  'Invalid or expired reset token': '重置链接无效或已过期',
  'If approved, a confirmation email will be sent': '该邮箱已注册，请查看邮件确认',
  'If the email exists, a reset link has been sent.': '如果该邮箱已注册，重置链接已发送',
  'Not authenticated': '未登录，请先登录',
  'Invalid token type': '令牌类型无效',
  'Token has been revoked': '令牌已被吊销',
  'Missing tenant context': '缺少租户信息',
  'Not a member of this tenant': '不属于该组织',
  'Invalid role': '角色无效',
  'Insufficient permissions': '权限不足',
  'An unexpected error occurred': '服务器内部错误，请稍后重试',
}

export function useToast() {
  const message = useMessage()

  return {
    success(msg: string) { message.success(msg) },
    error(msg: string) { message.error(msg) },
    warning(msg: string) { message.warning(msg) },
    info(msg: string) { message.info(msg) },
    apiError(e: unknown, fallback = '操作失败') {
      const err = e as { response?: { data?: { detail?: unknown; error?: { message?: string } } } }
      let detail = err?.response?.data?.error?.message || ''
      const rawDetail = err?.response?.data?.detail
      if (Array.isArray(rawDetail)) {
        const first = rawDetail[0] as { msg?: string; loc?: string[] } | undefined
        detail = first?.msg || ''
      } else if (typeof rawDetail === 'string') {
        detail = rawDetail
      }
      // 去掉 Pydantic "Value error, " 前缀
      detail = detail.replace(/^Value error,\s*/, '')
      const translated = FRONTEND_ERRORS[detail] || detail || fallback
      message.error(translated)
    },
  }
}
