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

cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV })
const db = cloud.database()
const _ = db.command

exports.main = async event => {
  const { OPENID } = cloud.getWXContext()
  const { postId, favorited } = event
  if (!postId) throw new Error('postId is required')

  const existed = await db.collection('postFavorites').where({ postId, openid: OPENID }).limit(1).get()
  let delta = 0

  if (favorited && !existed.data.length) {
    await db.collection('postFavorites').add({ data: { postId, openid: OPENID, createdAt: Date.now() } })
    delta = 1
  }

  if (!favorited && existed.data.length) {
    await db.collection('postFavorites').doc(existed.data[0]._id).remove()
    delta = -1
  }

  if (delta) {
    await db.collection('posts').doc(postId).update({ data: { 'counts.favorites': _.inc(delta) } })
  }

  const post = await db.collection('posts').doc(postId).get()
  return { favorited: Boolean(favorited), favorites: post.data.counts?.favorites || 0 }
}

