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

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

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

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

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

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