text: const
    { Command } = require('reconlx'),
    { MessageEmbed } = require("discord.js"),
    { colors } = require('../../Settings/embed.json');
  
  module.exports = new Command({
    name: 'dm',
    aliases: [],
    description: 'sends a user a dm',
    usage: '',
    permissions: { client: [], user: [] },
    cooldown: { global: '', user: '' },
    category: 'Fun',
    slashCommand: true,
    prefixCommand: false,
    ephemeralDefer: true,
    options: [
      {
        name: 'toggle',
        description: 'toggles the ability to send you user-made dms',
        type: 'SUB_COMMAND',
        options: [
          {
            name: 'user_to_toggle',
            description: 'the user you want to toggle, leave this empty to toggle all users ("*").',
            type: 'USER',
            required: false
          }
        ]
      },
      {
        name: 'list',
        description: 'lists all users you are currently blocking.',
        type: 'SUB_COMMAND'
      },
      {
        name: 'send',
        description: 'send a dm to a user of this guild',
        type: 'SUB_COMMAND',
        options: [
          {
            name: 'target',
            description: 'the user you want to send a dm to',
            type: 'USER',
            required: true
          },
          {
            name: 'message',
            description: `the message you want to send, /n for new line`,
            type: 'STRING',
            required: true
          },
          {
            name: 'as_mod',
            description: `shows 'a mod of {guild name}' instead of your name`,
            type: 'BOOLEAN',
            required: false
          }
        ]
      }
    ],
  
    run: async (client, _, interaction) => {
  
      const
        cmd = interaction.options.getSubcommand(),
        userToToggle = interaction.options.getUser('user_to_toggle'),
        messageTarget = interaction.options.getMember('target'),
        messageToSend = interaction.options.getString('message'),
        perm = interaction.member.permissions.has('MANAGE_MESSAGES'),
        asMod = (interaction.options.getBoolean('as_mod') && perm);
  
      let
        message, messageSender, newBlacklist, userBlacklist,
        blacklist = await client.db.get('dmCommandBlacklist');
  
      if (!asMod) messageSender = `\`${interaction.user.tag}\``;
  
      switch (cmd) {
        case 'toggle':
          userBlacklist = blacklist[interaction.member.id] || [];
          if (userToToggle?.id) {
            target = userToToggle.id;
            targetName = `user \`${userToToggle.tag}\``
          }
          else {
            target = '*';
            targetName = 'all users'
          }
  
          if (userBlacklist.includes(target)) {
            userBlacklist = userBlacklist.filter(entry => entry != target);
  
            message =
              `Your blacklist entry for \`${targetName}\` has been removed.\n` +
              `You can now receive dms created by ${targetName} from me.`;
          }
          else {
            userBlacklist.push(target);
  
            message =
              `Your blacklist entry for ${targetName} has been saved.\n` +
              `now ${target == '*' ? '`no one` will be' : `\`${targetName}\` isn't able`} able to send you dms by me.\n` +
              'This will not prevent guild moderators from sending dms to you.';
          }
  
          if (userBlacklist?.length > 0) newBlacklist = await Object.assign({}, blacklist, { [interaction.member.id]: userBlacklist });
          else delete blacklist[interaction.member.id];
  
          await client.db.set('dmCommandBlacklist', newBlacklist || blacklist);
  
          interaction.editReply(message);
          break;
  
        case 'list':
          userBlacklist = (await client.db.get('dmCommandBlacklist'))[interaction.user.id],
            listMessage = [];
  
          if (!userBlacklist) listMessage = '> You are not blocking any users.';
          else if (userBlacklist.includes('*')) listMessage = '> You are blocking all users.'
          else {
            for (const entry of userBlacklist) {
              try {
                await interaction.guild.members.fetch(entry);
              } catch { continue }
              listMessage += `> <@${entry}> (${entry})\n`;
            }
          }
  
          let listEmbed = new MessageEmbed()
            .setTitle('Your blacklist for the `/dm send` command')
            .setDescription(
              'You are blocking the following guild members:\n' +
              listMessage
            )
            .setColor(colors.discord.BURPLE)
            .setFooter({
              text:
                `run '/dm toggle' without arguments to toggle all users and\n` +
                `run '/dm toggle' with the 'user_to_toggle' argument to toggle a specific user.`
            });
  
          interaction.editReply({ embeds: [listEmbed] });
          break;
  
        case 'send':
          userBlacklist = blacklist[messageTarget.id] || [];
  
          if ((userBlacklist.includes(messageTarget.id) || userBlacklist.includes('*')) && !asMod) {
            const errorMsg =
              'You are not allowed to send dms to that user!' +
              `${perm ? '\nUse the `as_mod` option to force the message to send.' : ''}`;
  
            return interaction.editReply({ content: errorMsg });
          }
  
          let embed = new MessageEmbed()
            .setTitle('You got a message!')
            .setDescription(
              `From: **${messageSender || 'a guild moderator'}**\n` +
              `Guild: \`${interaction.guild.name}\`\n\n` +
              messageToSend
            )
            .setColor(colors.discord.BURPLE)
            .setFooter({
              text:
                `If you don't want to receive user-made dms from me, run /dm toggle in any server.\n` +
                'If someone abuses this command to spam, please message me.'
            });
  
          try {
            await messageTarget.send({ embeds: [embed] });
            interaction.editReply('Message sent!');
          }
          catch {
            interaction.editReply(`I couldn't message this member!`)
          };
          break;
  
        default: throw new SyntaxError(`The arg '${cmd}' of let cmd is not handled`);
      }
  
    }
  })