// 云函数入口文件
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, userInfo } = event

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

    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 isMember = members.some(m => m.openid === openid)

        if (isMember) {
            return { success: true, msg: '已在房间内' }
        }

        // 检查人数限制（最多8人）
        if (members.length >= 8) {
            return { success: false, msg: '房间人数已满（最多8人）' }
        }

        // 加入房间
        const newMember = {
                openid: openid,
                avatarUrl: userInfo?.avatarUrl || 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0',
                nickName: userInfo?.nickName || '微信用户',
                location: null,
                joinedAt: new Date()
            }

            await roomRef.update({
                data: {
                    members: _.push(newMember)
                }
            })
        }

        return {
            success: true,
            msg: '加入成功'
        }

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