import { showError } from '@/lib/feedback'

export type TencentActionError = Error & {
  errorCode?: string
  status?: number
}

export function notifyTencentActionError(error: unknown, fallbackMessage: string) {
  const message = resolveTencentActionMessage(error, fallbackMessage)
  console.error(error)
  showError(message)
}

export function resolveTencentActionMessage(error: unknown, fallbackMessage: string) {
  const normalizedError = error as TencentActionError
  const errorCode = String(normalizedError?.errorCode || '').trim()
  const message = normalizedError instanceof Error ? normalizedError.message.trim() : ''

  if (errorCode === 'missing_redeem_code') {
    return '请输入兑换码'
  }

  if (errorCode === 'session_not_ready') {
    return '当前会话还不能兑换，请先完成扫码并确认角色信息'
  }

  if (errorCode === 'session_not_found' || errorCode === 'not_found') {
    return '当前会话不存在或已过期，请重新生成二维码'
  }

  if (errorCode === 'session_closed' || errorCode === 'gone') {
    return '当前会话已关闭，请重新生成二维码'
  }

  if (errorCode === 'dependency_unavailable') {
    return '后端依赖暂不可用，请检查浏览器或 OCR 服务是否已就绪'
  }

  if (errorCode === 'invalid_request') {
    return '请求参数不完整，请检查输入后重试'
  }

  if (errorCode === 'conflict') {
    return '当前会话状态已变化，请刷新后重试'
  }

  return message || fallbackMessage
}
