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

const tempRoles = require('../../model/tempRoles')
const { parseDuration } = require('../../utils/duration')

module.exports = {
  data: {
    name: 'role',
    description: 'Assign or remove a role for a single member.',
    default_member_permissions: PermissionFlagsBits.ManageRoles.toString(),
    options: [
      {
        name: 'add',
        description: 'Add a role to a member, optionally temporary.',
        type: ApplicationCommandOptionType.Subcommand,
        options: [
          { name: 'user', description: 'Member', type: ApplicationCommandOptionType.User, required: true },
          { name: 'role', description: 'Role to add', type: ApplicationCommandOptionType.Role, required: true },
          { name: 'duration', description: 'Optional — makes this temporary, e.g. 1h, 2d, 7d', type: ApplicationCommandOptionType.String, required: false },
        ],
      },
      {
        name: 'remove',
        description: 'Remove a role from a member.',
        type: ApplicationCommandOptionType.Subcommand,
        options: [
          { name: 'user', description: 'Member', type: ApplicationCommandOptionType.User, required: true },
          { name: 'role', description: 'Role to remove', type: ApplicationCommandOptionType.Role, required: true },
        ],
      },
    ],
  },
  async execute(interaction) {
    const sub = interaction.options.getSubcommand()
    const user = interaction.options.getUser('user', true)
    const role = interaction.options.getRole('role', true)
    const member = interaction.guild.members.cache.get(user.id)

    if (!member) {
      await interaction.reply({ content: 'That user is not a member of this server.', ephemeral: true })
      return
    }

    if (sub === 'add') {
      await member.roles.add(role.id)
      const durationInput = interaction.options.getString('duration')
      if (!durationInput) {
        await interaction.reply({ content: `Added ${role} to ${user.tag}.`, ephemeral: true })
        return
      }
      const ms = parseDuration(durationInput)
      if (!ms) {
        await interaction.reply({
          content: `Added ${role}, but "${durationInput}" isn't a valid duration so it won't expire automatically. Use e.g. 1h, 2d, 7d.`,
          ephemeral: true,
        })
        return
      }
      const expiresAt = new Date(Date.now() + ms)
      await tempRoles.add({ guildId: interaction.guildId, userId: user.id, roleId: role.id, expiresAt, createdBy: interaction.user.id })
      await interaction.reply({ content: `Added ${role} to ${user.tag} until ${expiresAt.toLocaleString()}.`, ephemeral: true })
      return
    }

    if (sub === 'remove') {
      await member.roles.remove(role.id)
      await tempRoles.remove(interaction.guildId, user.id, role.id)
      await interaction.reply({ content: `Removed ${role} from ${user.tag}.`, ephemeral: true })
    }
  },
}
