'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 'profile': {
        // 查询用户资料
        const res = await db.collection('users')
          .doc(uid)
          .get()

        if (!res.data || res.data.length === 0) {
          // 尝试兼容 user 集合
          const res2 = await db.collection('users')
            .doc(uid)
            .get()
          if (!res2.data || res2.data.length === 0) {
            return { code: -1, message: '用户不存在' }
          }
          const user = res2.data[0]
          return {
            code: 0,
            data: {
              avatarUrl: user.avatarUrl || '',
              nickName: user.nickName || '毛球用户',
              membership: user.membership || { type: 'free', expireAt: null }
            }
          }
        }

        const user = res.data[0]
        return {
          code: 0,
          data: {
            avatarUrl: user.avatarUrl || user.wx_avatar_url || '',
            nickName: user.nickName || user.wx_nickname || '毛球用户',
            membership: user.membership || { type: 'free', expireAt: null }
          }
        }
      }

      case 'stats': {
        // 统计用户数据
        let petCount = 0
        let recordCount = 0
        let pendingScheduleCount = 0

        try {
          const petsRes = await db.collection('pets')
            .where({ user_id: uid })
            .count()
          petCount = petsRes.total || 0
        } catch (e) {
          // 集合可能不存在
        }

        try {
          const recordsRes = await db.collection('health_records')
            .where({ user_id: uid })
            .count()
          recordCount = recordsRes.total || 0
        } catch (e) {
          // 集合可能不存在
        }

        try {
          const schedulesRes = await db.collection('schedules')
            .where({ user_id: uid, status: 'pending' })
            .count()
          pendingScheduleCount = schedulesRes.total || 0
        } catch (e) {
          // 集合可能不存在
        }

        return {
          code: 0,
          data: { petCount, recordCount, pendingScheduleCount }
        }
      }

      case 'updateProfile': {
        const { nickName, avatarUrl, phone } = event
        await db.collection('users').doc(uid).update({
          nickName: nickName || '',
          avatarUrl: avatarUrl || '',
          phone: phone || '',
          updatedAt: Date.now()
        })
        return { code: 0, message: '更新成功' }
      }

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