import { SlashCommandBuilder, ChatInputCommandInteraction, PermissionFlagsBits, ChannelType } from 'discord.js';
import { SlashCommand } from '../../utils/types';
import { settingsStore } from '../../config/state';
import { context } from '../../config/context';
import { LoggingService } from '../../services/loggingService';

const command: SlashCommand = {
  guildOnly: true,
  data: new SlashCommandBuilder()
    .setName('configure')
    .setDescription('Setzt Basis-Einstellungen des Bots (gildenspezifisch).')
    .addChannelOption((opt) =>
      opt.setName('welcome_channel').setDescription('Kanal fuer Willkommensnachrichten').addChannelTypes(ChannelType.GuildText)
    )
    .addChannelOption((opt) => opt.setName('log_channel').setDescription('Kanal fuer Logs').addChannelTypes(ChannelType.GuildText))
    .addBooleanOption((opt) => opt.setName('automod').setDescription('Automod an/aus'))
    .addNumberOption((opt) => opt.setName('spam_threshold').setDescription('Spam-Schwelle (Nachrichten im Zeitfenster)'))
    .addNumberOption((opt) => opt.setName('spam_window_ms').setDescription('Spam-Zeitfenster in Millisekunden'))
    .addNumberOption((opt) => opt.setName('spam_timeout_minutes').setDescription('Timeout-Dauer (Minuten) bei Spam'))
    .addStringOption((opt) => opt.setName('link_whitelist').setDescription('Kommagetrennte Link-Whitelist (Domains)'))
    .addBooleanOption((opt) => opt.setName('leveling').setDescription('Level-System an/aus'))
    .addBooleanOption((opt) => opt.setName('dynamic_voice').setDescription('Dynamische Voice Channels an/aus'))
    .addChannelOption((opt) =>
      opt.setName('voice_lobby').setDescription('Voice-Lobby fuer dynamische Channels').addChannelTypes(ChannelType.GuildVoice)
    )
    .addStringOption((opt) => opt.setName('voice_template').setDescription('Name-Template, z.B. {user}s Channel'))
    .addIntegerOption((opt) => opt.setName('voice_user_limit').setDescription('Userlimit fuer dynamische Channels'))
    .addRoleOption((opt) => opt.setName('support_role').setDescription('Support-Rolle fuer Tickets'))
    .setDefaultMemberPermissions(PermissionFlagsBits.ManageGuild),
  async execute(interaction: ChatInputCommandInteraction) {
    if (!interaction.guildId) return;
    const guildSetting: any = settingsStore.get(interaction.guildId) ?? {};
    const welcome = interaction.options.getChannel('welcome_channel');
    const logChannel = interaction.options.getChannel('log_channel');
    const automod = interaction.options.getBoolean('automod');
    const spamThreshold = interaction.options.getNumber('spam_threshold');
    const spamWindowMs = interaction.options.getNumber('spam_window_ms');
    const spamTimeoutMinutes = interaction.options.getNumber('spam_timeout_minutes');
    const linkWhitelist = interaction.options.getString('link_whitelist');
    const leveling = interaction.options.getBoolean('leveling');
    const dynamicVoice = interaction.options.getBoolean('dynamic_voice');
    const voiceLobby = interaction.options.getChannel('voice_lobby');
    const voiceTemplate = interaction.options.getString('voice_template');
    const voiceUserLimit = interaction.options.getInteger('voice_user_limit');
    const supportRole = interaction.options.getRole('support_role');

    if (welcome) guildSetting.welcomeChannelId = welcome.id;
    if (logChannel) guildSetting.logChannelId = logChannel.id;
    if (automod !== null) guildSetting.automodEnabled = automod;
    if (spamThreshold !== null || spamWindowMs !== null || spamTimeoutMinutes !== null || linkWhitelist !== null) {
      guildSetting.automodConfig = {
        ...(guildSetting.automodConfig ?? {}),
        spamThreshold: spamThreshold ?? guildSetting.automodConfig?.spamThreshold,
        windowMs: spamWindowMs ?? guildSetting.automodConfig?.windowMs,
        spamTimeoutMinutes: spamTimeoutMinutes ?? guildSetting.automodConfig?.spamTimeoutMinutes,
        linkWhitelist:
          linkWhitelist !== null
            ? linkWhitelist
                .split(',')
                .map((s) => s.trim())
                .filter(Boolean)
            : guildSetting.automodConfig?.linkWhitelist
      };
    }
    if (leveling !== null) guildSetting.levelingEnabled = leveling;
    if (dynamicVoice !== null) guildSetting.dynamicVoiceEnabled = dynamicVoice;
    if (voiceLobby || voiceTemplate || voiceUserLimit !== null) {
      guildSetting.dynamicVoiceConfig = {
        ...(guildSetting.dynamicVoiceConfig ?? {}),
        lobbyChannelId: voiceLobby?.id ?? guildSetting.dynamicVoiceConfig?.lobbyChannelId,
        categoryId: voiceLobby?.parentId ?? guildSetting.dynamicVoiceConfig?.categoryId,
        template: voiceTemplate ?? guildSetting.dynamicVoiceConfig?.template,
        userLimit: voiceUserLimit ?? guildSetting.dynamicVoiceConfig?.userLimit
      };
    }
    if (supportRole) guildSetting.supportRoleId = supportRole.id;

    const updated = await settingsStore.set(interaction.guildId, guildSetting);
    context.logging = new LoggingService(updated.logChannelId);

    await interaction.reply({ content: 'Einstellungen gespeichert.', ephemeral: true });
  }
};

export default command;
