// In-memory per-guild filter state (word list + allowlist), loaded at startup
// and refreshed on config change — the messageCreate handler runs on every
// message, so it must never hit the DB per message (per the spec's
// performance note).
const filterWords = require('../model/filterWords')
const filterAllowlist = require('../model/filterAllowlist')

const cache = new Map() // guildId -> { words, allowRoles: Set, allowChannels: Set }

async function load(guildId) {
  const [words, roles, channels] = await Promise.all([
    filterWords.list(guildId),
    filterAllowlist.getRoles(guildId),
    filterAllowlist.getChannels(guildId),
  ])
  const entry = { words, allowRoles: new Set(roles), allowChannels: new Set(channels) }
  cache.set(guildId, entry)
  return entry
}

// Lazy-loads on first access per guild (e.g. the first message after boot).
async function getOrLoad(guildId) {
  return cache.get(guildId) || load(guildId)
}

// Called by /filter and /filterallow after any mutation.
function refresh(guildId) {
  return load(guildId)
}

module.exports = { getOrLoad, refresh }
