'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 { petId, type, page, pageSize } = event
        let query = db.collection('health_records').where({ user_id: uid })

        if (petId) {
          query = db.collection('health_records').where({
            user_id: uid,
            pet_id: petId,
          })
        }

        if (type && type !== 'all') {
          const where = petId
            ? { user_id: uid, pet_id: petId, type }
            : { user_id: uid, type }
          query = db.collection('health_records').where(where)
        }

        const p = page || 1
        const ps = pageSize || 50
        const skip = (p - 1) * ps

        const res = await query
          .orderBy('date', 'desc')
          .skip(skip)
          .limit(ps)
          .get()

        return {
          code: 0,
          data: { list: res.data || [], total: res.affectedDocs !== undefined ? res.affectedDocs : res.data.length },
        }
      }

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

      case 'add': {
        const { pet_id, type, title, date, nextDate, hospital, doctor, description,
          vaccineName, batchNumber, dewormType, dewormBrand, diagnosis, medications,
          images, cost, tags } = event
        if (!pet_id || !type || !date) {
          return { code: -1, message: '请填写必填项（宠物、类型、日期）' }
        }
        const now = Date.now()
        const recordData = {
          user_id: uid,
          pet_id,
          type,
          title: title || '',
          date,
          nextDate: nextDate || '',
          hospital: hospital || '',
          doctor: doctor || '',
          description: description || '',
          vaccineName: vaccineName || '',
          batchNumber: batchNumber || '',
          dewormType: dewormType || '',
          brand: dewormBrand || '',
          diagnosis: diagnosis || '',
          medications: medications || [],
          images: images || [],
          cost: cost || 0,
          tags: tags || [],
          createdAt: now,
          updatedAt: now,
        }
        const res = await db.collection('health_records').add(recordData)
        return { code: 0, data: { _id: res.id }, message: '添加成功' }
      }

      case 'update': {
        const { recordId, ...updateFields } = event
        if (!recordId) {
          return { code: -1, message: '缺少记录ID' }
        }
        delete updateFields.action
        delete updateFields.uid
        updateFields.updatedAt = Date.now()
        await db.collection('health_records').doc(recordId).update(updateFields)
        return { code: 0, message: '更新成功' }
      }

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

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