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

const guildConfig = require('../../model/guildConfig')

module.exports = {
  data: {
    name: 'news',
    description: 'View or set the channel news posts are announced to.',
    default_member_permissions: PermissionFlagsBits.ManageGuild.toString(),
    options: [
      {
        name: 'channel',
        description: 'Channel for news announcements. Omit to view the current setting.',
        type: ApplicationCommandOptionType.Channel,
        channel_types: [ChannelType.GuildText],
        required: false,
      },
    ],
  },
  async execute(interaction) {
    const channel = interaction.options.getChannel('channel')
    if (!channel) {
      const currentId = await guildConfig.getNewsChannelId(interaction.guildId)
      const content = currentId ? `News channel is set to <#${currentId}>.` : 'No news channel is set yet.'
      await interaction.reply({ content, ephemeral: true })
      return
    }
    await guildConfig.setNewsChannelId(interaction.guildId, channel.id)
    await interaction.reply({ content: `News channel set to ${channel}.`, ephemeral: true })
  },
}
