import { ChatInputCommandInteraction, EmbedBuilder, PermissionFlagsBits, SlashCommandBuilder } from 'discord.js';
import { settingsStore } from '../../config/state';
import { SlashCommand } from '../../utils/types';

const command: SlashCommand = {
  guildOnly: true,
  data: new SlashCommandBuilder()
    .setName('welcome')
    .setDescription('Loest die konfigurierte Willkommensnachricht aus.')
    .setDefaultMemberPermissions(PermissionFlagsBits.ManageGuild),
  async execute(interaction: ChatInputCommandInteraction) {
    if (!interaction.guildId || !interaction.guild) {
      await interaction.reply({ content: 'Dieser Befehl ist nur in Guilds verfuegbar.', ephemeral: true });
      return;
    }
    const cfg = settingsStore.get(interaction.guildId) ?? {};
    const welcome = cfg.welcomeConfig || cfg.automodConfig?.welcomeConfig;
    if (!welcome?.enabled || !welcome.channelId) {
      await interaction.reply({ content: 'Willkommensnachrichten sind fuer diesen Server nicht konfiguriert.', ephemeral: true });
      return;
    }
    const channel = interaction.guild.channels.cache.get(welcome.channelId) || (await interaction.guild.channels.fetch(welcome.channelId).catch(() => null));
    if (!channel || !channel.isTextBased()) {
      await interaction.reply({ content: 'Ziel-Channel fuer Willkommensnachrichten ist ungueltig.', ephemeral: true });
      return;
    }
    const colorVal = parseInt((welcome.embedColor || '00ff99').replace('#', ''), 16);
    const embed = new EmbedBuilder()
      .setTitle(welcome.embedTitle || 'Willkommen!')
      .setDescription(welcome.embedDescription || 'Schön, dass du da bist.')
      .setColor(isNaN(colorVal) ? 0x00ff99 : colorVal)
      .setFooter({ text: welcome.embedFooter || '' });
    const files: any[] = [];
    if (welcome.embedThumbnailData && welcome.embedThumbnailData.startsWith('data:')) {
      const [meta, b64] = welcome.embedThumbnailData.split(',');
      const ext = meta.includes('gif') ? 'gif' : 'png';
      const buf = Buffer.from(b64, 'base64');
      const name = `welcome-thumb.${ext}`;
      files.push({ attachment: buf, name });
      embed.setThumbnail(`attachment://${name}`);
    } else if (welcome.embedThumbnail) {
      embed.setThumbnail(welcome.embedThumbnail);
    }
    if (welcome.embedImageData && welcome.embedImageData.startsWith('data:')) {
      const [meta, b64] = welcome.embedImageData.split(',');
      const ext = meta.includes('gif') ? 'gif' : 'png';
      const buf = Buffer.from(b64, 'base64');
      const name = `welcome-image.${ext}`;
      files.push({ attachment: buf, name });
      embed.setImage(`attachment://${name}`);
    } else if (welcome.embedImage) {
      embed.setImage(welcome.embedImage);
    }
    await channel.send({ embeds: [embed], files }).catch(async () => {
      await interaction.reply({ content: 'Senden der Willkommensnachricht ist fehlgeschlagen.', ephemeral: true });
    });
    if (!interaction.replied && !interaction.deferred) {
      await interaction.reply({ content: 'Willkommensnachricht gesendet.', ephemeral: true });
    }
  }
};

export default command;
