import { SlashCommandBuilder, EmbedBuilder, PermissionFlagsBits } from 'discord.js';
import fetch from 'node-fetch';
import { ensureDiscordEmoji } from '../lib/image-convert.js';

export default {
  data: new SlashCommandBuilder()
    .setName('emoji')
    .setDescription('Tambah emoji custom')
    .setDefaultMemberPermissions(PermissionFlagsBits.ManageGuildExpressions)
    .addSubcommand(s => s
      .setName('add')
      .setDescription('Tambah emoji dari URL atau attachment')
      .addStringOption(o => o.setName('name').setDescription('Nama emoji (a-z, 0-9, _)').setRequired(true))
      .addStringOption(o => o.setName('url').setDescription('URL gambar/GIF'))
      .addAttachmentOption(o => o.setName('file').setDescription('File gambar/GIF'))),
  async execute(interaction) {
    const name = interaction.options.getString('name').replace(/[^a-z0-9_]/gi, '_').slice(0, 32);
    const url = interaction.options.getString('url');
    const file = interaction.options.getAttachment('file');

    const source = file?.url || url;
    if (!source) return interaction.reply({ content: '❌ Kasih URL atau attachment', ephemeral: true });

    await interaction.deferReply({ ephemeral: true });
    try {
      const res = await fetch(source);
      if (!res.ok) throw new Error(`HTTP ${res.status}`);
      let buf = Buffer.from(await res.arrayBuffer());

      // Terima file sampai 1 MB (Discord sendiri limit 256 KB, kita resize otomatis di bawah)
      if (buf.length > 1024 * 1024) {
        throw new Error(`File ${(buf.length / 1024).toFixed(0)} KB > 1 MB limit.`);
      }

      // Convert WebP dll -> PNG/GIF, lalu auto-resize ke bawah 256 KB (transparansi terjaga)
      buf = await ensureDiscordEmoji(buf);

      if (buf.length > 256 * 1024) {
        throw new Error(`Gagal compress di bawah 256 KB (hasil ${(buf.length / 1024).toFixed(0)} KB). Coba gambar lebih simpel.`);
      }
      const emoji = await interaction.guild.emojis.create({ attachment: buf, name });
      await interaction.editReply({
        embeds: [new EmbedBuilder()
          .setTitle('✅ Emoji ditambah')
          .setColor(0x10b981)
          .setDescription(`<${emoji.animated ? 'a' : ''}:${emoji.name}:${emoji.id}> \`:${emoji.name}:\``)],
      });
    } catch (e) {
      await interaction.editReply({ content: `❌ ${e.message}` });
    }
  },
};
