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

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

module.exports = {
  data: {
    name: 'filterallow',
    description: 'Manage roles/channels that bypass the filter entirely.',
    default_member_permissions: PermissionFlagsBits.ManageGuild.toString(),
    options: [
      {
        name: 'role',
        description: 'Toggle a role in/out of the filter bypass list.',
        type: ApplicationCommandOptionType.Subcommand,
        options: [{ name: 'role', description: 'Role to toggle', type: ApplicationCommandOptionType.Role, required: true }],
      },
      {
        name: 'channel',
        description: 'Toggle a channel in/out of the filter bypass list.',
        type: ApplicationCommandOptionType.Subcommand,
        options: [{ name: 'channel', description: 'Channel to toggle', type: ApplicationCommandOptionType.Channel, required: true }],
      },
      {
        name: 'list',
        description: 'Show current filter bypass roles/channels.',
        type: ApplicationCommandOptionType.Subcommand,
        options: [],
      },
    ],
  },
  async execute(interaction) {
    const sub = interaction.options.getSubcommand()

    if (sub === 'role') {
      const role = interaction.options.getRole('role', true)
      const nowAllowed = await filterAllowlist.toggleRole(interaction.guildId, role.id)
      await filterCache.refresh(interaction.guildId)
      await interaction.reply({ content: `${role} is ${nowAllowed ? 'now' : 'no longer'} bypassing the filter.`, ephemeral: true })
      return
    }

    if (sub === 'channel') {
      const channel = interaction.options.getChannel('channel', true)
      const nowAllowed = await filterAllowlist.toggleChannel(interaction.guildId, channel.id)
      await filterCache.refresh(interaction.guildId)
      await interaction.reply({ content: `${channel} is ${nowAllowed ? 'now' : 'no longer'} bypassing the filter.`, ephemeral: true })
      return
    }

    if (sub === 'list') {
      const [roles, channels] = await Promise.all([
        filterAllowlist.getRoles(interaction.guildId),
        filterAllowlist.getChannels(interaction.guildId),
      ])
      const roleText = roles.length ? roles.map((id) => `<@&${id}>`).join(', ') : 'none'
      const channelText = channels.length ? channels.map((id) => `<#${id}>`).join(', ') : 'none'
      await interaction.reply({ content: `Bypass roles: ${roleText}\nBypass channels: ${channelText}`, ephemeral: true })
    }
  },
}
