const cloud = require('wx-server-sdk')

cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV })
const db = cloud.database()

// Generate a unique handle from openid
function makeHandle(openid) {
  const suffix = openid.slice(-6).toLowerCase()
  return `@user_${suffix}`
}

// Deterministic gradient swatch (.gradient-avatar-1..6) from the user's openid, so
// a user who hasn't set a real avatar always gets the same stable colour.
function gradientAvatarKey(seed) {
  let h = 5381
  for (let i = 0; i < seed.length; i++) {
    h = ((h << 5) + h) ^ seed.charCodeAt(i)
    h >>>= 0
  }
  return `gradient-avatar-${(h % 6) + 1}`
}

exports.main = async event => {
  const { OPENID } = cloud.getWXContext()
  if (!OPENID) throw new Error('no openid in wx context')

  const now = Date.now()
  const existed = await db.collection('users').where({ openid: OPENID }).limit(1).get()

  if (existed.data.length) {
    const user = existed.data[0]
    await db.collection('users').doc(user._id).update({
      data: { lastLoginAt: now }
    })
    return {
      openid: OPENID,
      user: { ...user, lastLoginAt: now },
      isNew: false
    }
  }

  // New user — create with sensible defaults
  const avatarKey = gradientAvatarKey(OPENID)
  const user = {
    openid: OPENID,
    nickname: event.userInfo?.nickname || '宠物达人',
    handle: makeHandle(OPENID),
    avatarKey,
    avatarUrl: '',
    profileCompleted: false,
    location: '',
    yearsWithPets: 0,
    level: 1,
    bio: '',
    verified: false,
    stats: { posts: 0, following: 0, followers: 0 },
    preferences: { notifications: true, nearbyVisible: true },
    createdAt: now,
    lastLoginAt: now
  }

  const result = await db.collection('users').add({ data: user })
  return { openid: OPENID, user: { _id: result._id, ...user }, isNew: true }
}
