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

module.exports = {
  name: 'guildMemberAdd',
  
  async execute(member, client, supabase) {
    if (!supabase) return;
    
    try {
      const { data: serverConfig } = await supabase
        .from('federation_servers')
        .select('tier, status')
        .eq('guild_id', member.guild.id)
        .eq('status', 'approved')
        .maybeSingle();
      
      if (!serverConfig) return;
      
      const { data: ban } = await supabase
        .from('federation_bans')
        .select('*')
        .eq('user_id', member.id)
        .eq('active', true)
        .maybeSingle();
      
      if (!ban) return;
      
      const isPremium = serverConfig.tier === 'premium';
      const isCritical = ban.severity === 'critical';
      
      if (!isPremium && !isCritical) {
        return;
      }
      
      const severityColors = { low: 0xffff00, medium: 0xff9900, high: 0xff3300, critical: 0xff0000 };
      const severityEmojis = { low: '⚠️', medium: '🔶', high: '🔴', critical: '☠️' };
      
      const alertEmbed = new EmbedBuilder()
        .setColor(severityColors[ban.severity])
        .setTitle(`${severityEmojis[ban.severity]} Federation Alert: Flagged User Joined`)
        .setThumbnail(member.displayAvatarURL())
        .addFields(
          { name: 'User', value: `${member.user.tag}\n\`${member.id}\``, inline: true },
          { name: 'Severity', value: ban.severity.toUpperCase(), inline: true },
          { name: 'Reason', value: ban.reason || 'No reason provided' }
        )
        .setFooter({ text: 'AeThex Federation Protection' })
        .setTimestamp();
      
      const { data: config } = await supabase
        .from('server_config')
        .select('modlog_channel')
        .eq('guild_id', member.guild.id)
        .maybeSingle();
      
      if (config?.modlog_channel) {
        const logChannel = await client.channels.fetch(config.modlog_channel).catch(() => null);
        if (logChannel) {
          await logChannel.send({ embeds: [alertEmbed] });
        }
      }
      
      if (isCritical) {
        try {
          await member.ban({ reason: `[Federation] Global ban: ${ban.reason}` });
          
          alertEmbed.setTitle(`${severityEmojis[ban.severity]} Federation Auto-Ban: Critical Threat Removed`);
          alertEmbed.addFields({ name: 'Action Taken', value: 'User was automatically banned' });
          
          await supabase.from('federation_alerts').update({
            delivered: true,
            delivered_at: new Date().toISOString(),
            action_taken: 'auto_ban'
          }).eq('guild_id', member.guild.id).eq('ban_id', ban.id);
          
        } catch (banError) {
          console.error('[Federation] Failed to auto-ban:', banError.message);
          alertEmbed.addFields({ name: 'Action Required', value: 'Auto-ban failed. Please ban manually.' });
        }
      } else if (isPremium) {
        try {
          await member.kick(`[Federation] Global ban (${ban.severity} severity): ${ban.reason}`);
          alertEmbed.addFields({ name: 'Action Taken', value: 'User was automatically kicked (Premium Protection)' });
          
          await supabase.from('federation_alerts').update({
            delivered: true,
            delivered_at: new Date().toISOString(),
            action_taken: 'auto_kick'
          }).eq('guild_id', member.guild.id).eq('ban_id', ban.id);
        } catch (kickError) {
          console.error('[Federation] Failed to auto-kick:', kickError.message);
          alertEmbed.addFields({ name: 'Action Required', value: 'Auto-kick failed. Please remove user manually.' });
        }
      }
      
      const owner = await member.guild.fetchOwner().catch(() => null);
      if (owner && ban.severity === 'critical') {
        try {
          const dmEmbed = new EmbedBuilder()
            .setColor(0xff0000)
            .setTitle('Federation Alert: Critical Threat')
            .setDescription(`A user on the global ban list (Critical severity) joined **${member.guild.name}** and was automatically banned.`)
            .addFields(
              { name: 'User', value: `${member.user.tag} (\`${member.id}\`)` },
              { name: 'Reason', value: ban.reason }
            )
            .setTimestamp();
          
          await owner.send({ embeds: [dmEmbed] });
        } catch (dmError) {
        }
      }
      
    } catch (error) {
      console.error('[Federation Protection] Error:', error.message);
    }
  },
};
