const { SlashCommandBuilder } = require('discord.js');
const { simpleEmbed } = require('../functions/embeds.js');
const { Minecraft, Users } = require('../functions/models.js');
const { applyUsername } = require('../functions/utils.js');

module.exports = {
  data: new SlashCommandBuilder()
    .setName('whitelist')
    .setDescription('Whitelist yourself on the Minecraft server')
    .addStringOption(option => option
      .setName('code')
      .setDescription('6 digit code from Minecraft')
      .setRequired(true)),

  async execute(interaction) {
    const code = interaction.options.getString('code');

    if (code.length !== 6) return await interaction.reply({ embeds: [simpleEmbed('The code must be 6 digits long')], ephemeral: true });
    const user = await Users.findOne({ where: { id: interaction.user.id } });

    if (!user) return await interaction.reply({ embeds: [simpleEmbed('There was an error while finding the user')], ephemeral: true });
    if (user.minecraftUuid) return await interaction.reply({ embeds: [simpleEmbed('You are already whitelisted')], ephemeral: true });

    try {
      const minecraftCol = await Minecraft.findOne({ where: { code: code } });

      if (!minecraftCol) return await interaction.reply({ embeds: [simpleEmbed('The code was not linked with a Minecraft account')], ephemeral: true });

      if (minecraftCol.whitelisted) return await interaction.reply({ embeds: [simpleEmbed('Minecraft account already whitelisted')], ephemeral: true });


      minecraftCol.whitelisted = true;
      delete minecraftCol.code;

      user.minecraftUuid = minecraftCol.uuid;

      await minecraftCol.save();
      await user.save();

      await applyUsername(user, interaction.member);

      const role = await interaction.guild.roles.fetch(process.env.MINECRAFT_ROLE_ID);
      await interaction.member.roles.add(role);

      await interaction.reply({ embeds: [simpleEmbed('You are successfully whitelisted')], ephemeral: true });
    } catch (error) {
      console.error(error);
    }

  },
};
