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

module.exports = {
  name: 'guildMemberRemove',
  
  async execute(member, client, supabase) {
    if (!supabase) return;

    try {
      const { data: config } = await supabase
        .from('server_config')
        .select('goodbye_channel')
        .eq('guild_id', member.guild.id)
        .single();

      if (!config || !config.goodbye_channel) return;

      const channel = await client.channels.fetch(config.goodbye_channel).catch(() => null);
      if (!channel) return;

      const membershipDuration = getMembershipDuration(member.joinedTimestamp);
      const currentMemberCount = member.guild.memberCount;

      const roles = member.roles.cache
        .filter(r => r.id !== member.guild.id)
        .sort((a, b) => b.position - a.position)
        .map(r => r.name)
        .slice(0, 5);

      const goodbyeMessages = [
        `**${member.user.tag}** has left the server.`,
        `Goodbye, **${member.user.tag}**! We'll miss you!`,
        `**${member.user.tag}** just left. Hope to see you again!`,
        `**${member.user.tag}** has departed from the server.`,
      ];
      const randomMessage = goodbyeMessages[Math.floor(Math.random() * goodbyeMessages.length)];

      const embed = new EmbedBuilder()
        .setColor(0xef4444)
        .setAuthor({
          name: 'Member Left',
          iconURL: member.guild.iconURL({ size: 64 })
        })
        .setDescription(randomMessage)
        .setThumbnail(member.displayAvatarURL({ size: 512, dynamic: true }))
        .addFields(
          { 
            name: '👤 User', 
            value: member.user.tag, 
            inline: true 
          },
          { 
            name: '👥 Members Now', 
            value: currentMemberCount.toLocaleString(), 
            inline: true 
          },
          { 
            name: '⏰ Was Member For', 
            value: membershipDuration, 
            inline: true 
          }
        )
        .setFooter({ 
          text: `ID: ${member.id}`,
          iconURL: member.displayAvatarURL({ size: 32 })
        })
        .setTimestamp();

      if (roles.length > 0) {
        embed.addFields({
          name: '🎭 Had Roles',
          value: roles.map(r => `\`${r}\``).join(', ') + (member.roles.cache.size > 6 ? ` +${member.roles.cache.size - 6} more` : ''),
          inline: false
        });
      }

      await channel.send({ embeds: [embed] });

    } catch (error) {
      console.error('Goodbye error:', error.message);
    }
  }
};

function getMembershipDuration(joinedTimestamp) {
  if (!joinedTimestamp) return 'Unknown';
  
  const now = Date.now();
  const diff = now - joinedTimestamp;
  
  const seconds = Math.floor(diff / 1000);
  const minutes = Math.floor(seconds / 60);
  const hours = Math.floor(minutes / 60);
  const days = Math.floor(hours / 24);
  const months = Math.floor(days / 30);
  const years = Math.floor(days / 365);
  
  if (years > 0) {
    const remainingMonths = months % 12;
    return remainingMonths > 0 
      ? `${years}y ${remainingMonths}mo`
      : `${years} year${years > 1 ? 's' : ''}`;
  } else if (months > 0) {
    const remainingDays = days % 30;
    return remainingDays > 0
      ? `${months}mo ${remainingDays}d`
      : `${months} month${months > 1 ? 's' : ''}`;
  } else if (days > 0) {
    return `${days} day${days > 1 ? 's' : ''}`;
  } else if (hours > 0) {
    return `${hours} hour${hours > 1 ? 's' : ''}`;
  } else if (minutes > 0) {
    return `${minutes} minute${minutes > 1 ? 's' : ''}`;
  } else {
    return 'Just now';
  }
}
