import { SlashCommandBuilder, subtext } from "discord.js";
import { setTimeout } from "node:timers/promises";
import { getRandomInt } from "../../features/utilities.js";

const command = {
  data: new SlashCommandBuilder()
    .setName("dice")
    .setDescription("Lance un ou plusieurs dés")
    .addIntegerOption((option) =>
      option
        .setName("number")
        .setDescription("Nombre de dés a lancer")
        .setRequired(true)
    )
    .addIntegerOption((option) =>
      option
        .setName("faces")
        .setDescription("Nombre de faces sur le dé")
        .setRequired(true)
    ),
  async execute(interaction) {
    const number = interaction.options.getInteger("number");
    const faces = interaction.options.getInteger("faces");
    var sum = 0;
    var message = "Alors du coup... 🥁\n";
    var tails = 0;
    var heads = 0;

    if (faces === 1 || faces === 0) {
      await interaction.reply({
        content: "Ouais ouais, bien sur. Allez, bisous !",
        ephemeral: true,
      });
      return;
    }

    if (faces === 2) {
      message = message + subtext(`Pile = 1 et Face = 2\n`);
    }

    await interaction.reply(message);

    for (let i = 0; i < number; i++) {
      await setTimeout(1_500);
      let random = getRandomInt(faces) + 1;
      random === 1 ? tails++ : heads++;
      sum = sum + random;

      message = message + `[ ${random} ] ${i === number - 1 ? "\n" : " "}`;
      interaction.editReply(message);
    }

    if (number > 1 && faces > 2) {
      await setTimeout(1_000);
      message = message + subtext(`Soit au total : ${sum}`);
    }

    if (number > 1 && faces === 2) {
      await setTimeout(1_000);
      message =
        message +
        subtext(
          `Soit au total : ${sum}, ou bien ${tails} piles et ${heads} faces \n`
        );
    }

    interaction.editReply(message);
  },
};

export { command };
