const { PermissionFlagsBits, ApplicationCommandOptionType } = require('discord.js')

const filterWords = require('../../model/filterWords')
const filterCache = require('../../filter/filterCache')

module.exports = {
  data: {
    name: 'filter',
    description: 'Manage the banned-word filter.',
    default_member_permissions: PermissionFlagsBits.ManageGuild.toString(),
    options: [
      {
        name: 'add',
        description: 'Add a word to the filter.',
        type: ApplicationCommandOptionType.Subcommand,
        options: [
          { name: 'word', description: 'Word or phrase to ban', type: ApplicationCommandOptionType.String, required: true },
          {
            name: 'severity',
            description: 'Auto-action when triggered (default: delete)',
            type: ApplicationCommandOptionType.String,
            required: false,
            choices: [
              { name: 'Delete only', value: 'delete' },
              { name: 'Delete + warn', value: 'warn' },
              { name: 'Delete + mute (10m)', value: 'mute' },
            ],
          },
        ],
      },
      {
        name: 'remove',
        description: 'Remove a word from the filter.',
        type: ApplicationCommandOptionType.Subcommand,
        options: [
          { name: 'word', description: 'Word or phrase to remove', type: ApplicationCommandOptionType.String, required: true },
        ],
      },
      {
        name: 'list',
        description: 'List all filtered words.',
        type: ApplicationCommandOptionType.Subcommand,
        options: [],
      },
    ],
  },
  async execute(interaction) {
    const sub = interaction.options.getSubcommand()

    if (sub === 'add') {
      const word = interaction.options.getString('word', true)
      const severity = interaction.options.getString('severity') || 'delete'
      await filterWords.add({ guildId: interaction.guildId, word, severity, addedBy: interaction.user.id, addedByTag: interaction.user.tag })
      await filterCache.refresh(interaction.guildId)
      await interaction.reply({ content: `Added "${word}" to the filter (${severity}).`, ephemeral: true })
      return
    }

    if (sub === 'remove') {
      const word = interaction.options.getString('word', true)
      const removed = await filterWords.remove(interaction.guildId, word)
      await filterCache.refresh(interaction.guildId)
      await interaction.reply({ content: removed ? `Removed "${word}" from the filter.` : `"${word}" wasn't in the filter.`, ephemeral: true })
      return
    }

    if (sub === 'list') {
      const words = await filterWords.list(interaction.guildId)
      const content = words.length === 0 ? 'The filter list is empty.' : words.map((w) => `${w.word} (${w.severity})`).join('\n')
      await interaction.reply({ content, ephemeral: true })
    }
  },
}
