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

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

// Count a collection safely — returns 0 if the collection does not exist yet.
async function safeCount(collection, where) {
  try {
    const res = await db.collection(collection).where(where).count()
    return res.total || 0
  } catch (e) {
    return 0
  }
}

// Derive live stats from the source collections so the displayed numbers are
// always accurate instead of relying on a stored field that can drift.
async function computeStats(user) {
  const [posts, following, followers] = await Promise.all([
    safeCount('posts', { authorId: user._id }),
    safeCount('follows', { followerId: user._id }),
    safeCount('follows', { followeeId: user._id })
  ])
  return { posts, following, followers }
}

exports.main = async event => {
  const { OPENID } = cloud.getWXContext()
  if (!event.userId && !OPENID) throw new Error('no openid in wx context')
  const query = event.userId ? { _id: event.userId } : { openid: OPENID }
  const users = await db.collection('users').where(query).limit(1).get()
  const user = users.data[0] || null
  if (!user) return { user: null, pets: [] }

  const pets = await db.collection('pets').where({ ownerId: user._id }).limit(20).get()
  user.stats = await computeStats(user)

  return { user, pets: pets.data }
}
