// Roles/channels that bypass word/invite/spam filtering entirely (staff roles,
// bot-commands channels, etc.). Stored as CSV in guild_config rather than a
// separate table — short, rarely-changed lists.
const guildConfig = require('./guildConfig')

const ROLES_KEY = 'filter_allow_roles'
const CHANNELS_KEY = 'filter_allow_channels'

function parseCsv(value) {
  return value ? value.split(',').filter(Boolean) : []
}

async function getRoles(guildId) {
  return parseCsv(await guildConfig.get(guildId, ROLES_KEY))
}

async function getChannels(guildId) {
  return parseCsv(await guildConfig.get(guildId, CHANNELS_KEY))
}

// Toggle: adds the id if absent, removes it if present. Returns the new state (true = now allowed).
async function toggleRole(guildId, roleId) {
  const roles = await getRoles(guildId)
  const idx = roles.indexOf(roleId)
  if (idx === -1) roles.push(roleId)
  else roles.splice(idx, 1)
  await guildConfig.set(guildId, ROLES_KEY, roles.join(','))
  return idx === -1
}

async function toggleChannel(guildId, channelId) {
  const channels = await getChannels(guildId)
  const idx = channels.indexOf(channelId)
  if (idx === -1) channels.push(channelId)
  else channels.splice(idx, 1)
  await guildConfig.set(guildId, CHANNELS_KEY, channels.join(','))
  return idx === -1
}

module.exports = { getRoles, getChannels, toggleRole, toggleChannel }
