const { EmbedBuilder } = require("discord.js");

module.exports = {
  name: "guildBanAdd",
  async execute(ban, client) {
    const guild = ban.guild;

    const auditLogs = await guild.fetchAuditLogs({
      type: 22,
      limit: 1,
    }).catch(() => null);

    if (!auditLogs || !auditLogs.entries.first()) return;

    const entry = auditLogs.entries.first();
    const executor = entry.executor;

    if (!executor || executor.bot) return;
    if (executor.id === guild.ownerId) return;
    if (executor.id === client.user.id) return;

    const heatLevel = client.addHeat(executor.id, "member_ban");
    console.log(`[Sentinel] ${executor.tag} banned ${ban.user.tag} - Heat: ${heatLevel}/${client.HEAT_THRESHOLD}`);

    if (heatLevel >= client.HEAT_THRESHOLD) {
      const embed = new EmbedBuilder()
        .setColor(0xff0000)
        .setTitle("SENTINEL ALERT: Mass Ban Detected")
        .setDescription(`**User:** ${executor.tag} (${executor.id})\n**Action:** Banned ${heatLevel} members in rapid succession\n**Server:** ${guild.name}`)
        .setTimestamp();

      try {
        const member = await guild.members.fetch(executor.id);
        await member.ban({ reason: "[Sentinel] Anti-nuke triggered: Mass banning" });
        embed.addFields({ name: "Action Taken", value: "User has been banned" });
      } catch (err) {
        embed.addFields({ name: "Action Failed", value: `Could not ban user: ${err.message}` });
      }

      client.sendAlert(`SENTINEL ALERT`, embed);

      try {
        const owner = await guild.fetchOwner();
        await owner.send({ content: `[Sentinel Alert] ${executor.tag} was detected mass banning members and has been banned from ${guild.name}.`, embeds: [embed] });
      } catch (e) {}
    }
  },
};
