const { query } = require('../../utils/db')

const listByUser = (userId) =>
  query('SELECT stream_id FROM notification_subscriptions WHERE user_id = ? ORDER BY stream_id', [userId])

// Replace the user's whole subscription set in one transaction-ish pass: delete
// all, then insert the new set. Called by PUT — the request body is the complete
// desired set. `streams` is already validated against the catalog by the model.
async function replaceForUser(userId, streams) {
  await query('DELETE FROM notification_subscriptions WHERE user_id = ?', [userId])
  for (const streamId of streams) {
    await query('INSERT INTO notification_subscriptions (user_id, stream_id) VALUES (?, ?)', [userId, streamId])
  }
}

module.exports = { listByUser, replaceForUser }
