const { BASE_URL, SOURCE } = require('./config.js')
const { ensureLogin, clearLoginState } = require('./auth.js')

function cleanData(data = {}) {
  const result = {}
  Object.keys(data).forEach((key) => {
    const value = data[key]
    if (value !== undefined && value !== null && value !== '') result[key] = value
  })
  return result
}

function getModelSessionId() {
  try {
    if (wx.modelContext && wx.modelContext.getSessionId) {
      return wx.modelContext.getSessionId()
    }
  } catch (e) {}
  return ''
}

function sendRequest(path, options, token) {
  const method = options.method || 'GET'
  const data = cleanData(options.data || {})

  return new Promise((resolve) => {
    wx.request({
      url: `${BASE_URL}${path}`,
      method,
      data,
      header: {
        Authorization: `Bearer ${token}`,
        'X-Client-Source': SOURCE,
        'X-Skill-Name': options.skillName || 'activity',
        'X-Model-Session-Id': getModelSessionId()
      },
      success: (res) => {
        const body = res.data || {}
        if (res.statusCode >= 400) {
          resolve({
            traceId: body.traceId,
            safeMessage: body.safeMessage || body.message || '服务暂时不可用，请稍后重试',
            data: null,
            uiHints: body.uiHints || {},
            error: body.error || { code: `HTTP_${res.statusCode}`, retryable: false }
          })
          return
        }
        resolve(body)
      },
      fail: () => {
        resolve({
          safeMessage: '网络连接失败，请稍后重试',
          data: null,
          uiHints: {},
          error: { code: 'NETWORK_ERROR', retryable: true }
        })
      }
    })
  })
}

async function request(path, options = {}) {
  const token = await ensureLogin()
  const res = await sendRequest(path, options, token)

  if (res.error && res.error.code === 'UNAUTHORIZED' && options.retryOnUnauthorized !== false) {
    clearLoginState()
    const refreshedToken = await ensureLogin()
    return sendRequest(path, { ...options, retryOnUnauthorized: false }, refreshedToken)
  }

  return res
}

module.exports = { request }
