const app = getApp()

function unwrap(data) {
  if (data && typeof data === 'object' && 'code' in data && 'data' in data) {
    return data.data
  }
  return data
}

function request({ url, method = 'GET', data = {}, header = {} }) {
  return new Promise((resolve, reject) => {
    const app = getApp()
    if (app.globalData.token) {
        header['Authorization'] = `Bearer ${app.globalData.token}`
    }
    wx.request({
      url: `${app.globalData.baseUrl}${url.startsWith('/') ? '' : '/'}${url}`,
      method,
      data,
      header,
      success: (res) => {
        // Check HTTP status code
        if (res.statusCode >= 200 && res.statusCode < 300) {
             // Check logical code from backend wrapper
             if (res.data && typeof res.data === 'object' && 'code' in res.data) {
                 if (res.data.code < 200 || res.data.code >= 300) {
                     reject(res.data)
                     return
                 }
             }
             resolve(unwrap(res.data))
        } else {
             reject(res)
        }
      },
      fail: (err) => reject(err)
    })
  })
}

module.exports = { request }
