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

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

module.exports = {
  data: {
    name: 'autorole',
    description: 'View or set the role automatically assigned to new members on join.',
    default_member_permissions: PermissionFlagsBits.ManageGuild.toString(),
    options: [
      {
        name: 'role',
        description: 'Role to auto-assign on join. Omit to view the current setting.',
        type: ApplicationCommandOptionType.Role,
        required: false,
      },
    ],
  },
  async execute(interaction) {
    const role = interaction.options.getRole('role')
    if (!role) {
      const currentId = await guildConfig.getAutoRoleId(interaction.guildId)
      const content = currentId ? `Auto-role is set to <@&${currentId}>.` : 'No auto-role is set yet.'
      await interaction.reply({ content, ephemeral: true })
      return
    }
    await guildConfig.setAutoRoleId(interaction.guildId, role.id)
    await interaction.reply({ content: `Auto-role set to ${role}. New members will get this automatically.`, ephemeral: true })
  },
}
