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

module.exports = {
  name: "roleDelete",
  async execute(role, client) {
    if (!role.guild) return;

    const auditLogs = await role.guild.fetchAuditLogs({
      type: 32,
      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 === role.guild.ownerId) return;

    const heatLevel = client.addHeat(executor.id, "role_delete");
    console.log(`[Sentinel] ${executor.tag} deleted role @${role.name} - Heat: ${heatLevel}/${client.HEAT_THRESHOLD}`);

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

      try {
        const member = await role.guild.members.fetch(executor.id);
        await member.ban({ reason: "[Sentinel] Anti-nuke triggered: Mass role deletion" });
        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 role.guild.fetchOwner();
        await owner.send({ content: `[Sentinel Alert] ${executor.tag} was detected deleting multiple roles and has been banned from ${role.guild.name}.`, embeds: [embed] });
      } catch (e) {}
    }
  },
};
