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

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

// Reading a collection that was never created throws in WeChat 云开发, and this
// function reads `follows` before it ever adds to it — so on a fresh database the
// first follow would always fail. Create it up-front (no-op if it already exists).
async function ensureCollection(name) {
  try {
    await db.createCollection(name)
  } catch (e) {
    // Already-exists error is expected on every call after the first.
  }
}

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

  await ensureCollection('follows')

  const meRes = await db.collection('users').where({ openid: OPENID }).limit(1).get()
  if (!meRes.data.length) throw new Error('user not found')
  const meId = meRes.data[0]._id
  if (meId === targetUserId) throw new Error('cannot follow yourself')

  const targetRes = await db.collection('users').doc(targetUserId).get().catch(() => null)
  const target = targetRes && targetRes.data
  if (!target) throw new Error('target user not found')

  const existing = await db.collection('follows')
    .where({ followerId: meId, followeeId: targetUserId })
    .limit(1)
    .get()

  if (follow && !existing.data.length) {
    await db.collection('follows').add({
      data: {
        followerId: meId,
        followerOpenid: OPENID,
        followeeId: targetUserId,
        followeeOpenid: target.openid,
        createdAt: Date.now()
      }
    })
  } else if (!follow && existing.data.length) {
    await db.collection('follows').doc(existing.data[0]._id).remove()
  }

  // A friendship (汪友) is a mutual follow.
  const back = await db.collection('follows')
    .where({ followerId: targetUserId, followeeId: meId })
    .limit(1)
    .get()

  return { following: Boolean(follow), mutual: Boolean(follow) && back.data.length > 0 }
}
