import { ChannelType, PermissionFlagsBits, EmbedBuilder } from 'discord.js';
import { updateGuildConfig, audit } from '../../core/db.js';

export async function handleSetupInteraction(interaction, client) {
  const id = interaction.customId;
  const action = id.split('_')[1];

  await interaction.deferReply({ ephemeral: true });
  const guild = interaction.guild;
  const everyone = guild.roles.everyone;

  const result = { created: [], errors: [] };

  try {
    if (action === 'store' || action === 'full') {
      const cat = await guild.channels.create({ name: '🛒 STORE', type: ChannelType.GuildCategory });
      const products = await guild.channels.create({ name: 'products', type: ChannelType.GuildText, parent: cat });
      const orders = await guild.channels.create({ name: 'orders', type: ChannelType.GuildText, parent: cat });
      result.created.push(`store cat: ${cat}`, `products: ${products}`, `orders: ${orders}`);
    }

    if (action === 'ticket' || action === 'full') {
      const cat = await guild.channels.create({
        name: '🎫 TICKETS',
        type: ChannelType.GuildCategory,
        permissionOverwrites: [
          { id: everyone.id, deny: [PermissionFlagsBits.ViewChannel] },
        ],
      });
      const panel = await guild.channels.create({ name: 'open-ticket', type: ChannelType.GuildText, parent: cat });
      const logs = await guild.channels.create({ name: 'ticket-logs', type: ChannelType.GuildText, parent: cat });
      updateGuildConfig(guild.id, { ticket_category_id: cat.id });
      result.created.push(`ticket cat: ${cat}`, `panel: ${panel}`, `logs: ${logs}`);
      result.created.push(`ℹ️ jalankan \`/ticket panel channel:#open-ticket\` untuk kirim panel`);
    }

    if (action === 'welcome' || action === 'full') {
      const ch = await guild.channels.create({ name: 'welcome', type: ChannelType.GuildText });
      updateGuildConfig(guild.id, { welcome_channel_id: ch.id });
      result.created.push(`welcome: ${ch}`);
    }

    if (action === 'logs' || action === 'full') {
      const cat = await guild.channels.create({
        name: '📝 LOGS',
        type: ChannelType.GuildCategory,
        permissionOverwrites: [
          { id: everyone.id, deny: [PermissionFlagsBits.ViewChannel] },
        ],
      });
      const audit = await guild.channels.create({ name: 'audit-log', type: ChannelType.GuildText, parent: cat });
      const join = await guild.channels.create({ name: 'join-leave', type: ChannelType.GuildText, parent: cat });
      updateGuildConfig(guild.id, { log_channel_id: audit.id });
      result.created.push(`logs cat: ${cat}`, `audit: ${audit}`, `join-leave: ${join}`);
    }
  } catch (e) {
    result.errors.push(e.message);
  }

  const embed = new EmbedBuilder()
    .setTitle('🧰 Setup Complete')
    .setColor(result.errors.length ? 0xf59e0b : 0x10b981)
    .setDescription(result.created.join('\n') || '_(nothing created)_');
  if (result.errors.length) embed.addFields({ name: 'Errors', value: result.errors.join('\n') });

  audit(guild.id, interaction.user.id, `setup:${action}`, result);
  await interaction.editReply({ embeds: [embed] });
}
