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

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

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

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

