// Basic in-memory spam/rate-limit detection. Per-user message-rate tracking is
// the only stateful piece here (mass-mention/mass-emoji are per-message
// counts) — kept in memory rather than the DB since this runs on every
// message and needs to be fast.
const RATE_LIMIT_COUNT = 5
const RATE_LIMIT_WINDOW_MS = 5000
const MENTION_THRESHOLD = 5
const EMOJI_THRESHOLD = 10
const SWEEP_INTERVAL_MS = 5 * 60 * 1000

const history = new Map() // `${guildId}:${userId}` -> timestamps[]

function isRateLimited(guildId, userId) {
  const key = `${guildId}:${userId}`
  const now = Date.now()
  const timestamps = (history.get(key) || []).filter((t) => now - t < RATE_LIMIT_WINDOW_MS)
  timestamps.push(now)
  history.set(key, timestamps)
  return timestamps.length > RATE_LIMIT_COUNT
}

function isMassMention(message) {
  return message.mentions.users.size + message.mentions.roles.size > MENTION_THRESHOLD
}

const EMOJI_REGEX = /<a?:\w+:\d+>|\p{Extended_Pictographic}/gu

function isMassEmoji(content) {
  const count = (content.match(EMOJI_REGEX) || []).length
  return count > EMOJI_THRESHOLD
}

// Periodic cleanup so `history` doesn't grow unbounded over a long-running
// process — drops any key with no recent activity.
setInterval(() => {
  const now = Date.now()
  for (const [key, timestamps] of history) {
    if (timestamps.every((t) => now - t >= RATE_LIMIT_WINDOW_MS)) history.delete(key)
  }
}, SWEEP_INTERVAL_MS).unref()

module.exports = { isRateLimited, isMassMention, isMassEmoji }
