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

module.exports = {
  name: 'guildMemberAdd',
  
  async execute(member, client, supabase) {
    if (client.trackNewMember) {
      client.trackNewMember();
    }

    if (!supabase) return;

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

      if (!config) return;

      if (config.auto_role) {
        await member.roles.add(config.auto_role).catch(err => {
          console.warn(`Failed to add auto-role: ${err.message}`);
        });
      }

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

        const memberNumber = member.guild.memberCount;
        const accountAge = getAccountAge(member.user.createdTimestamp);
        const isNewAccount = (Date.now() - member.user.createdTimestamp) < 7 * 24 * 60 * 60 * 1000;

        const welcomeMessages = [
          `Welcome to **${member.guild.name}**, ${member}! We're glad you're here!`,
          `Hey ${member}, welcome to **${member.guild.name}**! Make yourself at home!`,
          `${member} just joined **${member.guild.name}**! Welcome aboard!`,
          `A wild ${member} appeared in **${member.guild.name}**! Welcome!`,
          `${member} has arrived! Welcome to **${member.guild.name}**!`,
        ];
        const randomMessage = welcomeMessages[Math.floor(Math.random() * welcomeMessages.length)];

        const embed = new EmbedBuilder()
          .setColor(0x22c55e)
          .setAuthor({
            name: 'Welcome to the server!',
            iconURL: member.guild.iconURL({ size: 64 })
          })
          .setDescription(randomMessage)
          .setThumbnail(member.displayAvatarURL({ size: 512, dynamic: true }))
          .addFields(
            { 
              name: '👤 Member', 
              value: `${member.user.tag}`, 
              inline: true 
            },
            { 
              name: '🔢 Member #', 
              value: `${memberNumber.toLocaleString()}`, 
              inline: true 
            },
            { 
              name: '📅 Account Age', 
              value: accountAge, 
              inline: true 
            }
          )
          .setFooter({ 
            text: `ID: ${member.id}`,
            iconURL: member.displayAvatarURL({ size: 32 })
          })
          .setTimestamp();

        if (isNewAccount) {
          embed.addFields({
            name: '⚠️ Notice',
            value: 'This is a new account (created within the last 7 days)',
            inline: false
          });
        }

        if (member.guild.rulesChannel) {
          embed.addFields({
            name: '📜 Get Started',
            value: `Check out the rules in ${member.guild.rulesChannel}`,
            inline: false
          });
        }

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

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

function getAccountAge(createdTimestamp) {
  const now = Date.now();
  const diff = now - createdTimestamp;
  
  const days = Math.floor(diff / (1000 * 60 * 60 * 24));
  const months = Math.floor(days / 30);
  const years = Math.floor(days / 365);
  
  if (years > 0) {
    return `${years} year${years > 1 ? 's' : ''} ago`;
  } else if (months > 0) {
    return `${months} month${months > 1 ? 's' : ''} ago`;
  } else if (days > 0) {
    return `${days} day${days > 1 ? 's' : ''} ago`;
  } else {
    return 'Today';
  }
}
