// 云函数入口文件
const cloud = require('wx-server-sdk')

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

exports.main = async (event, context) => {
    const { roomId, memberOpenid, location } = event

    if (!roomId || !memberOpenid || !location) {
        return { success: false, msg: '缺少必要参数' }
    }

    try {
        const roomRef = db.collection('rooms').doc(roomId)
        const room = await roomRef.get()

        if (!room.data) {
            return { success: false, msg: '房间不存在' }
        }

        // 查找成员索引
        const members = room.data.members || []
        const memberIndex = members.findIndex(m => m.openid === memberOpenid)

        if (memberIndex === -1) {
            return { success: false, msg: '成员不存在' }
        }

        // 更新成员位置
        members[memberIndex].location = location

        await roomRef.update({
            data: {
                members: _.set(members)  // 使用 _.set 强制覆写 members 字段
            }
        })

        return {
            success: true,
            msg: '位置更新成功'
        }

    } catch (err) {
        console.error(err)
        return {
            success: false,
            msg: '更新失败',
            error: err
        }
    }
}
