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

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

function isCloudFileId(v) {
  return typeof v === 'string' && v.startsWith('cloud://')
}

function extractMediaId(m) {
  if (!m) return ''
  if (typeof m === 'string') return m
  return m.fileId || m.fileID || m.url || ''
}

// Remove all docs matching `where`, tolerating a collection that was never created.
async function safeRemoveWhere(collection, where) {
  try {
    await db.collection(collection).where(where).remove()
  } catch (e) {
    /* collection missing or nothing to remove */
  }
}

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 (_) {
    return { ok: true } // already gone
  }
  const post = postRes.data
  if (!post) return { ok: true }
  if (post.authorOpenid !== OPENID) throw new Error('not allowed')

  await db.collection('posts').doc(event.postId).remove()

  // Decrement the author's post count (never below 0 in practice).
  if (post.authorId) {
    await db.collection('users').doc(post.authorId).update({
      data: { 'stats.posts': _.inc(-1) }
    }).catch(() => {})
  }

  // Best-effort cleanup of derived data so no orphans linger.
  await Promise.all([
    safeRemoveWhere('postLikes', { postId: event.postId }),
    safeRemoveWhere('postFavorites', { postId: event.postId }),
    safeRemoveWhere('comments', { postId: event.postId })
  ])

  // Best-effort removal of the post's uploaded media from storage.
  const fileList = (Array.isArray(post.media) ? post.media : [])
    .map(extractMediaId)
    .filter(isCloudFileId)
  if (fileList.length) {
    await cloud.deleteCloudFile({ fileList }).catch(() => {})
  }

  return { ok: true }
}
