'use strict'
const db = uniCloud.database()

exports.main = async (event, context) => {
  const { action, uid } = event

  if (!uid) {
    return { code: -1, message: '缺少用户标识' }
  }

  try {
    switch (action) {
      case 'list': {
        const res = await db.collection('pets')
          .where({ user_id: uid })
          .orderBy('createdAt', 'desc')
          .get()
        return {
          code: 0,
          data: res.data || []
        }
      }

      case 'detail': {
        const { petId } = event
        if (!petId) {
          return { code: -1, message: '缺少宠物ID' }
        }
        const res = await db.collection('pets').doc(petId).get()
        if (!res.data || res.data.length === 0) {
          return { code: -1, message: '宠物不存在' }
        }
        return { code: 0, data: res.data[0] }
      }

      case 'add': {
        const { name, species, breed, gender, birthday, weight, avatarUrl, color, neutered } = event
        if (!name) {
          return { code: -1, message: '请输入宠物名称' }
        }
        const now = Date.now()
        const petData = {
          user_id: uid,
          name,
          species: species || 'dog',
          breed: breed || '',
          gender: gender || 'male',
          birthday: birthday || '',
          weight: weight || null,
          avatarUrl: avatarUrl || '',
          color: color || '',
          neutered: neutered || false,
          createdAt: now,
          updatedAt: now,
        }
        const res = await db.collection('pets').add(petData)
        return { code: 0, data: { _id: res.id }, message: '添加成功' }
      }

      case 'update': {
        const { petId, ...updateFields } = event
        if (!petId) {
          return { code: -1, message: '缺少宠物ID' }
        }
        // 移除不允许更新的字段
        delete updateFields.action
        delete updateFields.uid
        updateFields.updatedAt = Date.now()
        await db.collection('pets').doc(petId).update(updateFields)
        return { code: 0, message: '更新成功' }
      }

      case 'delete': {
        const { petId } = event
        if (!petId) {
          return { code: -1, message: '缺少宠物ID' }
        }
        await db.collection('pets').doc(petId).remove()
        return { code: 0, message: '删除成功' }
      }

      default:
        return { code: -1, message: `未知操作: ${action}` }
    }
  } catch (err) {
    console.error('petManager error:', err)
    return { code: -1, message: err.message || '操作失败' }
  }
}
