// Detects Discord invite links and blocks any that don't resolve to the
// current guild (anti-raid/anti-advertising). An invite that fails to resolve
// (expired/invalid/vanity-only) is treated as foreign too — safer default
// than silently letting an unresolvable link through.
const INVITE_REGEX = /(?:discord\.gg|discord(?:app)?\.com\/invite)\/([a-zA-Z0-9-]+)/gi

async function containsForeignInvite(message) {
  const matches = [...message.content.matchAll(INVITE_REGEX)]
  if (matches.length === 0) return false

  for (const match of matches) {
    const code = match[1]
    try {
      const invite = await message.client.fetchInvite(code)
      if (invite.guild?.id !== message.guildId) return true
    } catch {
      return true
    }
  }
  return false
}

module.exports = { containsForeignInvite }
