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

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

async function fetchUsers(ids) {
  if (!ids.length) return []
  const out = []
  // _.in supports up to ~100 values; chunk to be safe
  for (let i = 0; i < ids.length; i += 100) {
    const chunk = ids.slice(i, i + 100)
    const res = await db.collection('users').where({ _id: _.in(chunk) }).limit(100).get()
    out.push(...res.data)
  }
  return out
}

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 type = event.type || 'friends'

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

  let ids = friendIds
  if (type === 'following') ids = followingIds
  else if (type === 'followers') ids = followerIds

  const users = await fetchUsers(ids)
  const list = users.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,
    counts: {
      following: followingIds.length,
      followers: followerIds.length,
      friends: friendIds.length
    }
  }
}
