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

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

// Discover other users to follow. Optional keyword filters by nickname.
exports.main = async event => {
  const { OPENID } = cloud.getWXContext()
  if (!OPENID) throw new Error('no openid in wx context')
  const meRes = await db.collection('users').where({ openid: OPENID }).limit(1).get()
  if (!meRes.data.length) throw new Error('user not found')
  const meId = meRes.data[0]._id
  const keyword = String(event.keyword || '').trim()

  const where = { _id: _.neq(meId) }
  if (keyword) where.nickname = db.RegExp({ regexp: keyword, options: 'i' })

  const usersRes = await db.collection('users')
    .where(where)
    .orderBy('lastLoginAt', 'desc')
    .limit(30)
    .get()

  const safeFollows = where2 =>
    db.collection('follows').where(where2).limit(500).get().catch(() => ({ data: [] }))
  const [followingRes, followerRes] = await Promise.all([
    safeFollows({ followerId: meId }),
    safeFollows({ followeeId: meId })
  ])
  const followingSet = new Set(followingRes.data.map(f => f.followeeId))
  const followerSet = new Set(followerRes.data.map(f => f.followerId))

  const list = usersRes.data.map(u => ({
    id: u._id,
    name: u.nickname || '用户',
    handle: u.handle || '',
    avatarKey: u.avatarKey || 'gradient-avatar-1',
    avatarUrl: u.avatarUrl || '',
    bio: u.bio || '',
    isFollowing: followingSet.has(u._id),
    isFriend: followingSet.has(u._id) && followerSet.has(u._id)
  }))

  return { list }
}
