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()
  if (!OPENID) throw new Error('no openid in wx context')
  if (!event.petId) throw new Error('petId is required')

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

  let pet
  try {
    pet = await db.collection('pets').doc(event.petId).get()
  } catch (_) {
    return { ok: true } // already gone
  }
  if (!pet.data) return { ok: true }
  if (pet.data.ownerId !== ownerId) throw new Error('not allowed')

  await db.collection('pets').doc(event.petId).remove()
  return { ok: true }
}
