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

export default {
  data: new SlashCommandBuilder()
    .setName('config')
    .setDescription('Atur konfigurasi bot')
    .setDefaultMemberPermissions(PermissionFlagsBits.Administrator)
    .addSubcommand(s => s.setName('view').setDescription('Lihat config'))
    .addSubcommand(s => s
      .setName('set-welcome')
      .setDescription('Set welcome channel')
      .addChannelOption(o => o.setName('channel').setDescription('Welcome channel').addChannelTypes(ChannelType.GuildText).setRequired(true)))
    .addSubcommand(s => s
      .setName('set-log')
      .setDescription('Set log channel')
      .addChannelOption(o => o.setName('channel').setDescription('Log channel').addChannelTypes(ChannelType.GuildText).setRequired(true)))
    .addSubcommand(s => s
      .setName('set-staff-role')
      .setDescription('Set staff role')
      .addRoleOption(o => o.setName('role').setDescription('Staff role').setRequired(true))),
  async execute(interaction) {
    const sub = interaction.options.getSubcommand();

    if (sub === 'view') {
      const cfg = getGuildConfig(interaction.guildId);
      const fmt = (id, type) => id ? `<#${id}>` : '_(tidak diset)_';
      const fmtRole = (id) => id ? `<@&${id}>` : '_(tidak diset)_';
      const embed = new EmbedBuilder()
        .setTitle('⚙️ Configuration')
        .setColor(0x5865f2)
        .addFields(
          { name: 'Ticket category', value: cfg.ticket_category_id ? `\`${cfg.ticket_category_id}\`` : '_-_', inline: true },
          { name: 'Welcome channel', value: fmt(cfg.welcome_channel_id), inline: true },
          { name: 'Log channel', value: fmt(cfg.log_channel_id), inline: true },
          { name: 'Staff role', value: fmtRole(cfg.staff_role_id), inline: true },
          { name: 'Currency', value: cfg.currency || 'IDR', inline: true },
        );
      return interaction.reply({ embeds: [embed], ephemeral: true });
    }

    const map = { 'set-welcome': 'welcome_channel_id', 'set-log': 'log_channel_id' };
    if (map[sub]) {
      const ch = interaction.options.getChannel('channel');
      updateGuildConfig(interaction.guildId, { [map[sub]]: ch.id });
      return interaction.reply({ content: `✅ Set ${sub.replace('set-', '')} → ${ch}`, ephemeral: true });
    }

    if (sub === 'set-staff-role') {
      const role = interaction.options.getRole('role');
      updateGuildConfig(interaction.guildId, { staff_role_id: role.id });
      return interaction.reply({ content: `✅ Staff role → ${role}`, ephemeral: true });
    }
  },
};
