const API_BASE = 'https://bigdata.dtacloud.cn/api'
const TOKEN_KEY = 'dlbdi-mini:token'

function getToken() {
  try {
    return wx.getStorageSync(TOKEN_KEY) || ''
  } catch (error) {
    return ''
  }
}

function requestAssist(data) {
  const token = getToken()
  return new Promise((resolve, reject) => {
    wx.request({
      url: `${API_BASE}/ai/wechat/assist`,
      method: 'POST',
      data,
      timeout: 15000,
      header: {
        'content-type': 'application/json',
        ...(token ? { Authorization: `Bearer ${token}` } : {}),
      },
      success(response) {
        if (response.statusCode >= 200 && response.statusCode < 300) {
          resolve(response.data || {})
          return
        }
        const body = response.data || {}
        reject(new Error(body.message || body.error || `请求失败：${response.statusCode}`))
      },
      fail(error) {
        reject(new Error(error && error.errMsg ? error.errMsg : '网络请求失败'))
      },
    })
  })
}

function apiSuccess(result, text) {
  return {
    isError: false,
    content: [{
      type: 'text',
      text: text || result.reply || '已获取研究院服务信息，请通过卡片查看。',
    }],
    structuredContent: result,
    _meta: {
      cards: result.cards || [],
      draft: result.draft || null,
      actions: result.actions || [],
      risk: result.risk || null,
    },
  }
}

function apiError(error, fallback) {
  return {
    isError: true,
    content: [{
      type: 'text',
      text: `${fallback || '服务助手暂时不可用'}：${error && error.message ? error.message : '未知错误'}。请引导用户稍后重试或手动打开小程序服务页。`,
    }],
  }
}

module.exports = {
  apiError,
  apiSuccess,
  requestAssist,
}
