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('ban')
    .setDescription('Ban a user')
    .setDefaultMemberPermissions(0)
    .addUserOption(option => option
      .setName('user')
      .setDescription('The user to ban')
      .setRequired(true))
    .addStringOption(option => option
      .setName('reason')
      .setDescription('Why ban the user')
      .setRequired(true)),

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

    try {
      await member.ban({ reason });
    } catch (error) {
      console.error(error);
      return await interaction.reply({ embeds: [simpleEmbed(`Error while banning ${member}`)], ephemeral: true });
    }

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

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

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

    await interaction.reply({ embeds: [simpleEmbed(`Banned ${member}`)], ephemeral: true });
  },
};
