const { EmbedBuilder } = require('discord.js');
const { getTrustLevelInfo, shouldAutoAction } = require('../utils/trustLevels');

module.exports = {
  name: 'guildMemberAdd',
  
  async execute(member, client, supabase) {
    if (!supabase) return;
    
    try {
      // Check if server is federation-verified (uses cache for performance)
      const isVerified = await client.isServerFederationVerified?.(member.guild.id);
      if (!isVerified) return;
      
      const { data: serverConfig } = await supabase
        .from('federation_servers')
        .select('tier, status, trust_level, reputation_score, verified')
        .eq('guild_id', member.guild.id)
        .eq('status', 'approved')
        .maybeSingle();
      
      // Double-check verification at database level
      if (!serverConfig || serverConfig.verified !== true) return;
      
      const { data: ban } = await supabase
        .from('federation_bans')
        .select('*')
        .eq('user_id', member.id)
        .eq('active', true)
        .maybeSingle();
      
      if (!ban) return;
      
      const trustLevel = serverConfig.trust_level || 'bronze';
      const isPremium = serverConfig.tier === 'premium';
      const trustInfo = getTrustLevelInfo(trustLevel);
      
      const actionDecision = shouldAutoAction(trustLevel, ban.severity, isPremium);
      
      if (actionDecision.action === 'alert' && ban.severity !== 'critical') {
        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: 'Trust Level', value: `${trustInfo.emoji} ${trustInfo.name}`, 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 (actionDecision.action === 'ban') {
        try {
          await member.ban({ reason: `[Federation] Global ban (${ban.severity}): ${ban.reason}` });
          
          alertEmbed.setTitle(`${severityEmojis[ban.severity]} Federation Auto-Ban: Threat Removed`);
          alertEmbed.addFields({ name: 'Action Taken', value: `User was automatically banned (${trustInfo.name} Protection)` });
          
          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 (actionDecision.action === 'kick') {
        try {
          await member.kick(`[Federation] Global ban (${ban.severity} severity): ${ban.reason}`);
          alertEmbed.addFields({ name: 'Action Taken', value: `User was automatically kicked (${trustInfo.name} 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.' });
        }
      }
      
      await supabase
        .from('federation_servers')
        .update({ last_activity: new Date().toISOString() })
        .eq('guild_id', member.guild.id);
      
      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);
    }
  },
};
