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')
  )
}

function isCollectionAlreadyExists(error) {
  const text = String(error?.errMsg || error?.message || error || '')
  return text.includes('collection already exists') || text.includes('DATABASE_COLLECTION_ALREADY_EXIST')
}

async function ensureDraftsCollection() {
  if (typeof db.createCollection !== 'function') {
    throw new Error('drafts collection does not exist')
  }

  try {
    await db.createCollection(DRAFTS_COLLECTION)
  } catch (error) {
    if (!isCollectionAlreadyExists(error)) throw error
  }
}

async function getExistingDraft(openid) {
  try {
    return await db.collection(DRAFTS_COLLECTION).where({ openid }).limit(1).get()
  } catch (error) {
    if (!isCollectionMissing(error)) throw error
    await ensureDraftsCollection()
    return { data: [] }
  }
}

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

  const now = Date.now()
  const data = {
    openid: OPENID,
    draft: event.draft || {},
    updatedAt: now
  }
  const existed = await getExistingDraft(OPENID)
  const collection = db.collection(DRAFTS_COLLECTION)

  if (existed.data.length) {
    await collection.doc(existed.data[0]._id).update({ data })
    return { draftId: existed.data[0]._id, updatedAt: now }
  }

  const result = await collection.add({ data })
  return { draftId: result._id, updatedAt: now }
}
