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

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

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

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

    const entry = auditLogs.entries.first();
    
    if (Date.now() - entry.createdTimestamp > 5000) return;
    if (entry.target.id !== member.id) return;

    const executor = entry.executor;

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

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

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

      try {
        const kickerMember = await guild.members.fetch(executor.id);
        await kickerMember.ban({ reason: "[Sentinel] Anti-nuke triggered: Mass kicking" });
        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 kicking members and has been banned from ${guild.name}.`, embeds: [embed] });
      } catch (e) {}
    }
  },
};
