const db = require('../db')

async function add({ guildId, word, severity, addedBy, addedByTag }) {
  await db.query(
    `INSERT INTO filter_words (guild_id, word, severity, added_by, added_by_tag)
     VALUES (?, ?, ?, ?, ?)
     ON DUPLICATE KEY UPDATE severity = VALUES(severity), added_by = VALUES(added_by), added_by_tag = VALUES(added_by_tag)`,
    [guildId, word.toLowerCase(), severity || 'delete', addedBy || null, addedByTag || null],
  )
}

// Returns true if a row was actually removed.
async function remove(guildId, word) {
  const res = await db.query('DELETE FROM filter_words WHERE guild_id = ? AND word = ?', [guildId, word.toLowerCase()])
  return Number(res.affectedRows || 0) > 0
}

async function list(guildId) {
  return db.query('SELECT word, severity FROM filter_words WHERE guild_id = ? ORDER BY word ASC', [guildId])
}

module.exports = { add, remove, list }
