// Per-user push-notification subscriptions (which streams a user opted into;
// applied to every device they register). The catalog is core's plus every
// installed module's, so it is read back through modules/registries rather than
// from a config file (MODULE_SYSTEM.md §1.8).

const db = require('./notificationSubs.db')
const { isValidStream } = require('../../modules/registries')

const getForUser = async (userId) => (await db.listByUser(userId)).map((r) => r.stream_id)

// Replace the user's subscription set. Ignores unknown ids and de-dupes, so a
// stale client can't create rows for streams that no longer exist. Returns the
// stored (cleaned) set.
async function setForUser(userId, streams) {
  const clean = [...new Set((Array.isArray(streams) ? streams : []).filter(isValidStream))]
  await db.replaceForUser(userId, clean)
  return clean
}

module.exports = { getForUser, setForUser }
