// 云函数入口文件
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 wxContext = cloud.getWXContext()
    const openid = wxContext.OPENID

    const { roomId, location } = event
    // location format: { lng: 116.1, lat: 39.1, address: "...", name: "..." }

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

    try {
        // 2026-02-02 Fix: 使用 Read-Modify-Write 模式避免复杂更新操作符报错
        // 先读取房间数据
        const roomRes = await db.collection('rooms').doc(roomId).get()
        const roomData = roomRes.data

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

        const members = roomData.members || []
        const memberIndex = members.findIndex(m => m.openid === openid)

        if (memberIndex === -1) {
            return { success: false, msg: '您尚未加入该房间' }
        }

        // 直接修改内存中的数组对象
        members[memberIndex].location = location

        // 2026-02-02 Fix: 使用 _.set 强制覆写 members 字段，解决 DuplicateWrite 索引冲突问题
        // 这通常是因为数据结构不一致或底层索引冲突导致的，set 指令会完全替换字段值
        await db.collection('rooms').doc(roomId).update({
            data: {
                members: _.set(members)
            }
        })

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

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