import { Events, EmbedBuilder } from 'discord.js';
import { getGuildConfig } from '../core/db.js';

export default {
  name: Events.GuildMemberAdd,
  async execute(member) {
    const cfg = getGuildConfig(member.guild.id);
    if (!cfg.welcome_channel_id) return;
    const ch = member.guild.channels.cache.get(cfg.welcome_channel_id);
    if (!ch) return;

    const accountAgeDays = Math.floor((Date.now() - member.user.createdTimestamp) / 86400000);

    const embed = new EmbedBuilder()
      .setTitle('👋 Welcome!')
      .setDescription(`Selamat datang ${member} di **${member.guild.name}**`)
      .addFields(
        { name: 'Member ke', value: `#${member.guild.memberCount}`, inline: true },
        { name: 'Account age', value: `${accountAgeDays} hari`, inline: true },
      )
      .setThumbnail(member.user.displayAvatarURL({ size: 256 }))
      .setColor(accountAgeDays < 7 ? 0xf59e0b : 0x10b981)
      .setTimestamp();

    if (accountAgeDays < 7) {
      embed.addFields({ name: '⚠️ New account', value: 'Akun baru (<7 hari) — staff harap monitor', inline: false });
    }

    await ch.send({ embeds: [embed] }).catch(() => {});

    // Log to audit channel
    if (cfg.log_channel_id && cfg.log_channel_id !== cfg.welcome_channel_id) {
      const log = member.guild.channels.cache.get(cfg.log_channel_id);
      if (log) {
        await log.send({
          embeds: [new EmbedBuilder()
            .setTitle('📥 Member Joined')
            .setDescription(`${member.user.tag} (\`${member.id}\`)`)
            .addFields({ name: 'Account age', value: `${accountAgeDays} hari` })
            .setColor(0x3b82f6)
            .setTimestamp()],
        }).catch(() => {});
      }
    }
  },
};
