// 云函数入口文件
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 { roomId, nickName } = 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 avatarColors = [
            'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0', // 微信默认头像
            'https://thirdwx.qlogo.cn/mmopen/vi_32/POgEwh4mIHO4nibH0KlMECNjjGxQUq24ZEaGT4poC6icRiccVGKSyXwibcPq4BWmiaIGuG1icwxaQX6grC9VemZoJ8rg/132', // 示例头像
            '/images/default-avatar.png'  // 本地默认头像
        ]
        const randomAvatar = avatarColors[Math.floor(Math.random() * avatarColors.length)]

        const newMember = {
            openid: `test_member_${Date.now()}`,
            avatarUrl: randomAvatar,
            nickName: nickName || '测试成员',
            location: null,  // 初始无位置
            isTestMember: true,  // 标记为测试成员
            joinedAt: new Date()
        }

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

        return {
            success: true,
            msg: '成员添加成功',
            member: newMember
        }

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