// 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-z0-9-]+)/gi

// Returns the first foreign (or unresolvable) invite code found in the message,
// or null if the message contains no foreign invites. Returning the code (rather
// than a bare boolean) lets the caller record which invite was blocked.
async function foreignInviteCode(message) {
  const matches = [...message.content.matchAll(INVITE_REGEX)]
  if (matches.length === 0) return null

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

module.exports = { foreignInviteCode }
