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

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()
const userCollection = db.collection('users')

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  const openid = wxContext.OPENID
  
  if (!openid) {
    return {
      code: 401,
      message: '未能获取到用户OpenID',
    }
  }
  
  try {
    // 查询用户是否已存在
    const userResult = await userCollection.where({
      userId: openid
    }).get()
    
    if (userResult.data.length > 0) {
      // 用户已存在，更新登录时间
      const user = userResult.data[0]
      await userCollection.doc(user._id).update({
        data: {
          lastLoginAt: db.serverDate()
        }
      })
      
      // 返回用户信息
      return {
        code: 200,
        message: '登录成功',
        data: {
          token: openid, // 简单实现，直接使用openid作为token
          user: {
            userId: user.userId,
            nickName: user.nickName,
            avatarUrl: user.avatarUrl,
            gender: user.gender,
            gameHistory: user.gameHistory || [],
            premiumUser: user.premiumUser || false,
            createdAt: user.createdAt,
            lastLoginAt: new Date(),
          }
        }
      }
    } else {
      // 用户不存在，创建新用户
      const now = db.serverDate()
      const newUser = {
        userId: openid,
        nickName: '游客' + openid.substring(openid.length - 6),
        avatarUrl: '',
        gender: 0,
        gameHistory: [],
        premiumUser: false,
        createdAt: now,
        lastLoginAt: now,
      }
      
      const addResult = await userCollection.add({
        data: newUser
      })
      
      // 返回用户信息
      return {
        code: 200,
        message: '注册成功',
        data: {
          token: openid,
          user: {
            ...newUser,
            createdAt: new Date(),
            lastLoginAt: new Date(),
          }
        }
      }
    }
  } catch (error) {
    console.error('登录失败:', error)
    return {
      code: 500,
      message: '登录失败: ' + error.message,
    }
  }
} 