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

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

async function safeGet(collection, where, limit = 200) {
  try {
    return await db.collection(collection).where(where).limit(limit).get()
  } catch (e) {
    return { data: [] }
  }
}

function formatTimeText(ts) {
  const diff = Date.now() - ts
  const mins = Math.floor(diff / 60000)
  if (mins < 1) return '刚刚'
  if (mins < 60) return `${mins} 分钟前`
  const hours = Math.floor(mins / 60)
  if (hours < 24) return `${hours} 小时前`
  const days = Math.floor(hours / 24)
  if (days === 1) return '昨天'
  if (days < 7) return `${days} 天前`
  const d = new Date(ts)
  return `${d.getMonth() + 1}月${d.getDate()}日`
}

// List a user's own posts. Defaults to the caller; pass authorId to view
// another user (only public posts are returned for others).
exports.main = async event => {
  const { OPENID } = cloud.getWXContext()
  if (!OPENID) throw new Error('no openid in wx context')

  let authorOpenid = OPENID
  let viewingSelf = true
  if (event.authorId) {
    const u = await db.collection('users').doc(event.authorId).get().catch(() => null)
    if (!u || !u.data) return { list: [] }
    authorOpenid = u.data.openid
    viewingSelf = authorOpenid === OPENID
  }

  const where = { authorOpenid }
  if (!viewingSelf) where.visibility = 'public'

  const res = await db.collection('posts')
    .where(where)
    .orderBy('createdAt', 'desc')
    .limit(50)
    .get()

  if (!res.data.length) return { list: [] }

  const postIds = res.data.map(p => p._id)
  const [likedRes, favRes] = await Promise.all([
    safeGet('postLikes', { openid: OPENID, postId: _.in(postIds) }),
    safeGet('postFavorites', { openid: OPENID, postId: _.in(postIds) })
  ])
  const likedSet = new Set(likedRes.data.map(l => l.postId))
  const favSet = new Set(favRes.data.map(f => f.postId))

  const list = res.data.map(post => ({
    _id: post._id,
    author: {
      id: post.authorId || '',
      name: post.authorSnapshot?.name || '用户',
      avatarKey: post.authorSnapshot?.avatarKey || 'gradient-avatar-1'
    },
    pet: post.petSnapshot || { name: '', breed: '' },
    body: post.content || '',
    topics: post.topics || [],
    media: Array.isArray(post.media)
      ? post.media.map(m => (typeof m === 'string' ? m : m && (m.url || m.fileId))).filter(Boolean)
      : [],
    mediaTone: post.mediaTone || 'pet-1',
    sticker: post.sticker || undefined,
    locationText: post.locationText || '',
    timeText: formatTimeText(post.createdAt || Date.now()),
    counts: {
      likes: post.counts?.likes || 0,
      comments: post.counts?.comments || 0,
      favorites: post.counts?.favorites || 0
    },
    likedByMe: likedSet.has(post._id),
    favoritedByMe: favSet.has(post._id)
  }))

  return { list }
}
