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

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

exports.main = async event => {
  const { OPENID } = cloud.getWXContext()
  const users = await db.collection('users').where({ openid: OPENID }).limit(1).get()
  if (!users.data.length) throw new Error('user not found')

  const pet = {
    ...(event.pet || {}),
    ownerId: users.data[0]._id,
    updatedAt: Date.now()
  }
  delete pet._id

  if (event.pet?._id) {
    await db.collection('pets').doc(event.pet._id).update({ data: pet })
    return { petId: event.pet._id }
  }

  const countRes = await db.collection('pets').where({ ownerId: users.data[0]._id }).count()
  if ((countRes.total || 0) >= MAX_PETS_PER_USER) {
    throw new Error(`最多只能添加 ${MAX_PETS_PER_USER} 只宠物`)
  }

  pet.createdAt = Date.now()
  const result = await db.collection('pets').add({ data: pet })
  return { petId: result._id }
}
