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

let accessToken = ''
let expiresAt = 0
let refreshing = null

function checkSession() {
  return new Promise((resolve) => {
    wx.checkSession({
      success: () => resolve(true),
      fail: () => resolve(false)
    })
  })
}

function loginWithCode(code) {
  return new Promise((resolve, reject) => {
    if (!code) {
      reject(new Error('微信登录失败，请稍后重试'))
      return
    }
    wx.request({
      url: `${BASE_URL}/api/auth/wechat-login`,
      method: 'POST',
      data: { code, source: SOURCE },
      success: (res) => {
        const body = res.data && res.data.data ? res.data.data : res.data
        if (res.statusCode >= 400 || !body || !body.accessToken) {
          reject(new Error((body && (body.safeMessage || body.message)) || '登录失败'))
          return
        }
        accessToken = body.accessToken
        expiresAt = Date.now() + (body.expiresIn || 7200) * 1000
        resolve(accessToken)
      },
      fail: reject
    })
  })
}

async function ensureLogin() {
  const now = Date.now()
  if (accessToken && expiresAt - now > 60 * 1000 && await checkSession()) {
    return accessToken
  }
  if (refreshing) return refreshing

  refreshing = new Promise((resolve, reject) => {
    wx.login({
      success: ({ code }) => {
        loginWithCode(code).then(resolve).catch(reject).finally(() => {
          refreshing = null
        })
      },
      fail: (err) => {
        refreshing = null
        reject(err)
      }
    })
  })

  return refreshing
}

function clearLoginState() {
  accessToken = ''
  expiresAt = 0
  refreshing = null
}

module.exports = { ensureLogin, clearLoginState }
