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

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

const ALLOWED_VISIBILITY = ['public', 'friends', 'private']

// Lightweight edit: only the post's text content and visibility can change here.
exports.main = async event => {
  const { OPENID } = cloud.getWXContext()
  if (!OPENID) throw new Error('no openid in wx context')
  if (!event.postId) throw new Error('postId is required')

  let postRes
  try {
    postRes = await db.collection('posts').doc(event.postId).get()
  } catch (_) {
    throw new Error('post not found')
  }
  const post = postRes.data
  if (!post) throw new Error('post not found')
  if (post.authorOpenid !== OPENID) throw new Error('not allowed')

  const data = { updatedAt: Date.now() }
  if (typeof event.content === 'string') {
    const content = event.content.trim()
    if (!content) throw new Error('content is required')
    data.content = content.slice(0, 2000)
  }
  if (typeof event.visibility === 'string' && ALLOWED_VISIBILITY.includes(event.visibility)) {
    data.visibility = event.visibility
  }

  await db.collection('posts').doc(event.postId).update({ data })
  return { ok: true }
}
