const { SlashCommandBuilder } = require('discord.js');
const { simpleEmbed } = require('../functions/embeds.js');
const { Users } = require('../functions/models.js');
const { client } = require('../index.js');

module.exports = {
  data: new SlashCommandBuilder()
    .setName('suspend')
    .setDescription('Suspend a user')
    .setDefaultMemberPermissions(0)
    .addUserOption(option => option
      .setName('user')
      .setDescription('The user to suspend')
      .setRequired(true))
    .addNumberOption(option => option
      .setName('time')
      .setDescription('The amount of time to suspend the user in minutes')
      .setRequired(true))
    .addStringOption(option => option
      .setName('reason')
      .setDescription('Why suspend the user')
      .setRequired(true)),

  async execute(interaction) {
    const time = interaction.options.getNumber('time');
    const member = interaction.options.getMember('user');
    const reason = interaction.options.getString('reason');

    await member.timeout(time * 60 * 1000, reason);

    const user = await Users.findOne({ where: { id: member.id } });
    if (!user) return await interaction.reply({ embeds: [simpleEmbed('Error while getting user information')], ephemeral: true });

    if (user.minecraftUuid) {
      await fetch(process.env.MINECRAFT_HOST + '/console', {
        method: 'POST',
        headers: {
          'content-type': 'text/plain',
        },
        body: `tempban ${user.minecraftUuid} ${time}m ${reason}`,
      });
    }

    const channel = client.channels.cache.get(process.env.MOD_LOG_CHANNEL_ID);
    await channel.send({ embeds: [simpleEmbed(`${interaction.user} suspended ${member} for **${time}** minutes, reason: **${reason}**`)] });

    await interaction.reply({ embeds: [simpleEmbed(`Suspended ${member} for **${time}** minutes`)], ephemeral: true });
  },
};
