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

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

// Reading a collection that was never created throws in WeChat 云开发, and this
// function reads `matches` before it ever adds to it — so the collection would
// never get created and every "like" would fail. Create it up-front (no-op if it
// already exists) to break that deadlock.
async function ensureCollection(name) {
  try {
    await db.createCollection(name)
  } catch (e) {
    // Already-exists error is expected on every call after the first.
  }
}

exports.main = async event => {
  const { OPENID } = cloud.getWXContext()
  const { petId } = event
  if (!petId) throw new Error('petId is required')

  await ensureCollection('matches')

  // Get current user and their pets
  const userRes = await db.collection('users').where({ openid: OPENID }).limit(1).get()
  if (!userRes.data.length) throw new Error('user not found')
  const userId = userRes.data[0]._id

  // Record this like (idempotent)
  const existed = await db.collection('matches').where({ fromOpenid: OPENID, petId }).limit(1).get()
  if (!existed.data.length) {
    await db.collection('matches').add({ data: { fromOpenid: OPENID, userId, petId, createdAt: Date.now() } })
  }

  // Check mutual match: does the target pet's owner like any of current user's pets?
  let matched = false
  try {
    const targetPetRes = await db.collection('pets').doc(petId).get()
    const targetOwnerId = targetPetRes.data?.ownerId
    if (targetOwnerId && targetOwnerId !== userId) {
      const targetOwnerRes = await db.collection('users').doc(targetOwnerId).get()
      const targetOpenid = targetOwnerRes.data?.openid
      if (targetOpenid) {
        const myPetsRes = await db.collection('pets').where({ ownerId: userId }).limit(20).get()
        const myPetIds = myPetsRes.data.map(p => p._id)
        if (myPetIds.length) {
          const reverseRes = await db.collection('matches')
            .where({ fromOpenid: targetOpenid, petId: _.in(myPetIds) })
            .limit(1)
            .get()
          matched = reverseRes.data.length > 0
        }
      }
    }
  } catch (_) {}

  return { matched }
}
