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

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

const MEDIA_TONES = ['pet-1', 'pet-2', 'pet-3']
const PET_TONES = { dog: 'gold', cat: 'purple', other: 'green' }

exports.main = async event => {
  const { OPENID } = cloud.getWXContext()
  const now = Date.now()
  const content = String(event.content || '').trim()
  if (!content) throw new Error('content is required')

  // Get author info first (required for snapshot)
  const userRes = await db.collection('users').where({ openid: OPENID }).limit(1).get()
  if (!userRes.data.length) throw new Error('user not found')
  const user = userRes.data[0]

  // Get pet snapshot if petId provided
  let petSnapshot = null
  if (event.petId) {
    try {
      const petRes = await db.collection('pets').doc(event.petId).get()
      if (petRes.data) {
        const p = petRes.data
        petSnapshot = { name: p.name, breed: p.breed, tone: PET_TONES[p.species] || 'green' }
      }
    } catch (_) {}
  }

  // Derive mediaTone from media count so similar posts look varied
  const mediaCount = Array.isArray(event.media) ? event.media.length : 0
  const mediaTone = event.mediaTone || MEDIA_TONES[(mediaCount + now) % 3]

  const post = {
    authorOpenid: OPENID,
    authorId: user._id,
    authorSnapshot: { name: user.nickname, avatarKey: user.avatarKey, avatarUrl: user.avatarUrl || '' },
    petId: event.petId || '',
    petSnapshot,
    content: content.slice(0, 2000),
    topics: Array.isArray(event.topics) ? event.topics : [],
    media: Array.isArray(event.media) ? event.media : [],
    mediaTone,
    sticker: event.sticker || null,
    locationText: event.locationText || '',
    location: (typeof event.latitude === 'number' && typeof event.longitude === 'number')
      ? { latitude: event.latitude, longitude: event.longitude }
      : null,
    visibility: event.visibility || 'public',
    counts: { likes: 0, comments: 0, shares: 0 },
    createdAt: now,
    updatedAt: now
  }

  const result = await db.collection('posts').add({ data: post })

  await db.collection('users').doc(user._id).update({
    data: { 'stats.posts': _.inc(1) }
  })

  return { postId: result._id }
}
