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

cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV }) // 使用当前云环境
const db = cloud.database()

// 云函数入口函数
exports.main = async (event, context) => {
    const wxContext = cloud.getWXContext()
    const openid = wxContext.OPENID

    const { userInfo, keywords, requirements, name, meetTime } = event

    try {
        // 计算过期时间（30天后）
        const expireTime = new Date(Date.now() + 30 * 24 * 60 * 60 * 1000)

        const res = await db.collection('rooms').add({
            data: {
                _openid: openid, // 创建者openid
                createdAt: db.serverDate(),
                expireTime: expireTime, // 过期时间
                status: 'active',
                name: name || '未命名聚会',
                meetTime: meetTime || '',
                keywords: keywords || '咖啡馆',
                requirements: requirements || '',
                members: [{
                    openid: openid,
                    avatarUrl: userInfo?.avatarUrl || 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0',
                    nickName: userInfo?.nickName || '发起人',
                    location: null, // 初始无位置
                    joinedAt: new Date()
                }],
                result: null
            }
        })

        return {
            success: true,
            roomId: res._id,
            msg: '创建成功'
        }
    } catch (err) {
        console.error(err)
        return {
            success: false,
            msg: '创建房间失败',
            error: err
        }
    }
}

