const cloud = require('wx-server-sdk')

cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV })
const db = cloud.database()
const DRAFTS_COLLECTION = 'drafts'

function isCollectionMissing(error) {
  const text = String(error?.errMsg || error?.message || error || '')
  return (
    text.includes('collection not exist') ||
    text.includes('collection not exists') ||
    text.includes('collection is not exists') ||
    text.includes('DATABASE_COLLECTION_NOT_EXIST') ||
    text.includes('-502005')
  )
}

exports.main = async () => {
  const { OPENID } = cloud.getWXContext()
  if (!OPENID) throw new Error('no openid in wx context')

  let res
  try {
    res = await db.collection(DRAFTS_COLLECTION).where({ openid: OPENID }).limit(1).get()
  } catch (error) {
    if (isCollectionMissing(error)) return { draft: null }
    throw error
  }

  if (!res.data.length) return { draft: null }
  const record = res.data[0]
  return { draft: record.draft || null, updatedAt: record.updatedAt }
}
