import { SlashCommandBuilder, EmbedBuilder, PermissionFlagsBits, ActionRowBuilder, ButtonBuilder, ButtonStyle } from 'discord.js';
import { snapshotGuild } from '../modules/server-clone/snapshot.js';
import { db } from '../core/db.js';

export default {
  data: new SlashCommandBuilder()
    .setName('clone')
    .setDescription('Clone struktur server (kategori, channel, role) ke server lain')
    .setDefaultMemberPermissions(PermissionFlagsBits.Administrator)
    .addSubcommand(s => s.setName('snapshot').setDescription('Buat snapshot server ini buat di-clone nanti'))
    .addSubcommand(s => s
      .setName('apply')
      .setDescription('Apply snapshot ke server ini')
      .addIntegerOption(o => o.setName('snapshot_id').setDescription('ID snapshot').setRequired(true))),
  async execute(interaction) {
    const sub = interaction.options.getSubcommand();

    if (sub === 'snapshot') {
      await interaction.deferReply({ ephemeral: true });
      const snapshot = await snapshotGuild(interaction.guild);
      const result = db.prepare(
        'INSERT INTO clone_snapshots (source_guild_id, created_by, data) VALUES (?, ?, ?)'
      ).run(interaction.guildId, interaction.user.id, JSON.stringify(snapshot));

      const embed = new EmbedBuilder()
        .setTitle('📸 Snapshot Created')
        .setColor(0x10b981)
        .addFields(
          { name: 'ID', value: `\`${result.lastInsertRowid}\``, inline: true },
          { name: 'Source', value: `\`${interaction.guild.name}\``, inline: true },
          { name: 'Categories', value: `${snapshot.categories.length}`, inline: true },
          { name: 'Channels', value: `${snapshot.channels.length}`, inline: true },
          { name: 'Roles', value: `${snapshot.roles.length}`, inline: true },
          { name: 'Emojis', value: `${snapshot.emojis.length}`, inline: true },
        )
        .setDescription([
          'Cara apply ke server lain:',
          '1. Invite bot ke server tujuan',
          `2. Run \`/clone apply snapshot_id:${result.lastInsertRowid}\` di server tujuan`,
        ].join('\n'));

      await interaction.editReply({ embeds: [embed] });
      return;
    }

    if (sub === 'apply') {
      const snapshotId = interaction.options.getInteger('snapshot_id');
      const row = db.prepare('SELECT * FROM clone_snapshots WHERE id = ?').get(snapshotId);
      if (!row) {
        return interaction.reply({ content: `❌ Snapshot \`${snapshotId}\` not found`, ephemeral: true });
      }
      const snapshot = JSON.parse(row.data);

      const embed = new EmbedBuilder()
        .setTitle('🔁 Apply Snapshot — Pilih yang mau dicopy')
        .setColor(0x5865f2)
        .setDescription(`Source server: **\`${snapshot.guild_name}\`**\nSnapshot ID: \`${snapshotId}\``)
        .addFields(
          { name: 'Categories', value: `${snapshot.categories.length}`, inline: true },
          { name: 'Channels', value: `${snapshot.channels.length}`, inline: true },
          { name: 'Roles', value: `${snapshot.roles.length}`, inline: true },
          { name: 'Emojis', value: `${snapshot.emojis.length}`, inline: true },
        )
        .setFooter({ text: '⚠️ Member, pesan, dan history TIDAK dicopy' });

      const r1 = new ActionRowBuilder().addComponents(
        new ButtonBuilder().setCustomId(`clone_apply:${snapshotId}:roles`).setLabel('Roles only').setStyle(ButtonStyle.Secondary),
        new ButtonBuilder().setCustomId(`clone_apply:${snapshotId}:channels`).setLabel('Channels only').setStyle(ButtonStyle.Secondary),
        new ButtonBuilder().setCustomId(`clone_apply:${snapshotId}:full`).setLabel('Full clone').setEmoji('🚀').setStyle(ButtonStyle.Success),
        new ButtonBuilder().setCustomId(`clone_cancel:${snapshotId}`).setLabel('Cancel').setStyle(ButtonStyle.Danger),
      );

      await interaction.reply({ embeds: [embed], components: [r1], ephemeral: true });
    }
  },
};
