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

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

exports.main = async event => {
  const { OPENID } = cloud.getWXContext()

  // Reading a non-existent collection throws in WeChat 云开发, and this function
  // starts with a read — so the collection would never get created by the later
  // add(). Create it up-front (no-op if it already exists) to break that deadlock.
  try {
    await db.createCollection('locations')
  } catch (e) {
    // -501001 / "already exists" is expected on every call after the first.
  }

  const now = Date.now()
  const loc = event.location || null
  const visible = Boolean(event.visible)
  const hasCoord = loc && typeof loc.latitude === 'number' && typeof loc.longitude === 'number'

  const data = {
    openid: OPENID,
    location: hasCoord ? { latitude: loc.latitude, longitude: loc.longitude } : null,
    // `nearbyPets` currently filters by distance in memory off `location`, so the
    // `visible` flag below is what gates discovery. `geo` is kept (Point form) only
    // to enable a future geoNear migration if the user base outgrows the in-memory
    // scan — it needs a manually-created geo index to be queried.
    geo: hasCoord && visible ? db.Geo.Point(loc.longitude, loc.latitude) : null,
    visible,
    updatedAt: now
  }

  const existed = await db.collection('locations').where({ openid: OPENID }).limit(1).get()
  if (existed.data.length) await db.collection('locations').doc(existed.data[0]._id).update({ data })
  else await db.collection('locations').add({ data })

  return { ok: true }
}
