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

module.exports = {
  name: 'messageCreate',
  
  async execute(message, client, supabase) {
    if (message.author.bot) return;
    if (!message.guild) return;

    const config = await getAutomodConfig(message.guild.id, client, supabase);
    if (!config) return;

    if (isExempt(message.member, config.exempt_roles)) return;

    let violation = null;

    if (config.links_enabled && containsLink(message.content)) {
      violation = { type: 'link', action: config.links_action };
    }

    if (!violation && config.invites_enabled && containsInvite(message.content)) {
      violation = { type: 'invite', action: 'delete' };
    }

    if (!violation && config.badwords?.length > 0 && containsBadWord(message.content, config.badwords)) {
      violation = { type: 'badword', action: 'delete' };
    }

    if (!violation && config.mentions_enabled && exceedsMentionLimit(message, config.mentions_limit)) {
      violation = { type: 'mentions', action: 'delete' };
    }

    if (!violation && config.spam_enabled) {
      const isSpam = await checkSpam(message, client, config.spam_threshold);
      if (isSpam) {
        violation = { type: 'spam', action: 'timeout' };
      }
    }

    if (violation) {
      await handleViolation(message, violation, client, supabase);
    }
  }
};

async function getAutomodConfig(guildId, client, supabase) {
  if (client.automodConfig?.has(guildId)) {
    return client.automodConfig.get(guildId);
  }

  if (!supabase) return null;

  try {
    const { data, error } = await supabase
      .from('automod_config')
      .select('*')
      .eq('guild_id', guildId)
      .single();

    if (error || !data) return null;

    client.automodConfig = client.automodConfig || new Map();
    client.automodConfig.set(guildId, data);

    return data;
  } catch {
    return null;
  }
}

function isExempt(member, exemptRoles) {
  if (!member || !exemptRoles || exemptRoles.length === 0) return false;
  
  if (member.permissions.has('Administrator')) return true;
  
  return member.roles.cache.some(role => exemptRoles.includes(role.id));
}

function containsLink(content) {
  const linkRegex = /https?:\/\/[^\s]+/gi;
  return linkRegex.test(content);
}

function containsInvite(content) {
  const inviteRegex = /(discord\.(gg|io|me|li)|discordapp\.com\/invite)\/[a-zA-Z0-9]+/gi;
  return inviteRegex.test(content);
}

function containsBadWord(content, badwords) {
  const lowerContent = content.toLowerCase();
  return badwords.some(word => {
    const regex = new RegExp(`\\b${escapeRegex(word)}\\b`, 'i');
    return regex.test(lowerContent);
  });
}

function escapeRegex(string) {
  return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}

function exceedsMentionLimit(message, limit) {
  const mentions = message.mentions.users.size + message.mentions.roles.size;
  return mentions > (limit || 5);
}

async function checkSpam(message, client, threshold) {
  client.spamTracker = client.spamTracker || new Map();
  
  const key = `${message.guild.id}-${message.author.id}`;
  const now = Date.now();
  const window = 5000;
  
  let userMessages = client.spamTracker.get(key) || [];
  userMessages = userMessages.filter(t => now - t < window);
  userMessages.push(now);
  client.spamTracker.set(key, userMessages);
  
  return userMessages.length >= (threshold || 5);
}

async function handleViolation(message, violation, client, supabase) {
  try {
    await message.delete().catch(() => {});

    const violationMessages = {
      link: '🔗 Links are not allowed in this server.',
      invite: '📨 Discord invites are not allowed.',
      badword: '🚫 Your message contained a banned word.',
      mentions: '📢 Too many mentions in your message.',
      spam: '🔄 Slow down! You\'re sending messages too fast.'
    };

    const dmEmbed = new EmbedBuilder()
      .setColor(0xef4444)
      .setTitle('⚠️ Message Removed')
      .setDescription(violationMessages[violation.type] || 'Your message violated server rules.')
      .setFooter({ text: message.guild.name })
      .setTimestamp();

    await message.author.send({ embeds: [dmEmbed] }).catch(() => {});

    if (violation.action === 'warn' && supabase) {
      await supabase.from('warnings').insert({
        guild_id: message.guild.id,
        user_id: message.author.id,
        user_tag: message.author.tag,
        moderator_id: client.user.id,
        moderator_tag: client.user.tag,
        reason: `Auto-mod: ${violation.type} violation`
      });
    }

    if (violation.action === 'timeout') {
      await message.member.timeout(5 * 60 * 1000, `Auto-mod: ${violation.type} violation`).catch(() => {});
    }

    const { data: config } = await supabase
      ?.from('server_config')
      .select('modlog_channel')
      .eq('guild_id', message.guild.id)
      .single() || { data: null };

    if (config?.modlog_channel) {
      const logChannel = await client.channels.fetch(config.modlog_channel).catch(() => null);
      if (logChannel) {
        const logEmbed = new EmbedBuilder()
          .setColor(0xf97316)
          .setTitle('🛡️ Auto-Mod Action')
          .addFields(
            { name: 'User', value: `${message.author.tag} (${message.author.id})`, inline: true },
            { name: 'Violation', value: violation.type, inline: true },
            { name: 'Action', value: violation.action, inline: true },
            { name: 'Channel', value: `<#${message.channel.id}>`, inline: true }
          )
          .setFooter({ text: 'Auto-Moderation' })
          .setTimestamp();

        await logChannel.send({ embeds: [logEmbed] });
      }
    }

  } catch (error) {
    console.error('Auto-mod violation handling error:', error);
  }
}
