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

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

function isCollectionMissing(error) {
  const text = String(error?.errMsg || error?.message || error || '')
  return (
    text.includes('collection not exist') ||
    text.includes('collection not exists') ||
    text.includes('collection is not exists') ||
    text.includes('DATABASE_COLLECTION_NOT_EXIST') ||
    text.includes('-502005')
  )
}

function isCollectionAlreadyExists(error) {
  const text = String(error?.errMsg || error?.message || error || '')
  return text.includes('collection already exists') || text.includes('DATABASE_COLLECTION_ALREADY_EXIST')
}

async function ensureCommentsCollection() {
  if (typeof db.createCollection !== 'function') {
    throw new Error('comments collection does not exist')
  }

  try {
    await db.createCollection(COMMENTS_COLLECTION)
  } catch (error) {
    if (!isCollectionAlreadyExists(error)) throw error
  }
}

async function addComment(data) {
  try {
    return await db.collection(COMMENTS_COLLECTION).add({ data })
  } catch (error) {
    if (!isCollectionMissing(error)) throw error
    await ensureCommentsCollection()
    return db.collection(COMMENTS_COLLECTION).add({ data })
  }
}

exports.main = async event => {
  const { OPENID } = cloud.getWXContext()
  if (!OPENID) throw new Error('no openid in wx context')

  const postId = String(event.postId || '').trim()
  const content = String(event.content || '').trim()
  if (!postId) throw new Error('postId is required')
  if (!content) throw new Error('content is required')

  const [postRes, userRes] = await Promise.all([
    db.collection('posts').doc(postId).get(),
    db.collection('users').where({ openid: OPENID }).limit(1).get()
  ])

  if (!postRes.data) throw new Error('post not found')
  if (!userRes.data.length) throw new Error('user not found')

  const now = Date.now()
  const user = userRes.data[0]
  const result = await addComment({
    postId,
    openid: OPENID,
    authorId: user._id,
    authorSnapshot: {
      name: user.nickname || '',
      avatarKey: user.avatarKey || 'gradient-avatar-1',
      avatarUrl: user.avatarUrl || ''
    },
    content: content.slice(0, 500),
    createdAt: now,
    updatedAt: now
  })

  await db.collection('posts').doc(postId).update({
    data: {
      'counts.comments': _.inc(1),
      updatedAt: now
    }
  })

  const updatedPost = await db.collection('posts').doc(postId).get()
  return {
    commentId: result._id,
    comments: updatedPost.data.counts?.comments || 0
  }
}
