const app = getApp()

function request(path, options = {}) {
  return new Promise((resolve, reject) => {
    wx.request({
      url: `${app.globalData.apiBase}${path}`,
      method: options.method || 'GET',
      data: options.data,
      header: {
        'Content-Type': 'application/json',
        Authorization: app.globalData.token ? `Bearer ${app.globalData.token}` : '',
        ...(options.header || {}),
      },
      success(res) {
        const body = res.data
        if (res.statusCode >= 200 && res.statusCode < 300 && body.code === 0) {
          resolve(body.data)
          return
        }
        reject(new Error(body.message || `HTTP ${res.statusCode}`))
      },
      fail: reject,
    })
  })
}

function login(phone, code) {
  return request('/api/auth/login', {
    method: 'POST',
    data: {
      loginType: 'phone_code',
      credential: phone,
      code,
    },
  }).then((data) => {
    app.globalData.token = data.token
    wx.setStorageSync('happy_up_token', data.token)
    return data
  })
}

function listChildren() {
  return request('/api/children')
}

module.exports = {
  request,
  login,
  listChildren,
}
