const { MessageEmbed, Permissions } = require("discord.js");
const ms = require("ms");

module.exports = {
  name: 'start',
  description: '🎉 Start a giveaway',
  options: [
    {
      name: 'duration',
      description: 'How long the giveaway should last for. Example values: 1m, 1h, 1d',
      type: 'STRING',
      required: true
    },
    {
      name: 'winners',
      description: 'How many winners the giveaway should have',
      type: 'INTEGER',
      required: true
    },
    {
      name: 'prize',
      description: 'What the prize of the giveaway should be',
      type: 'STRING',
      required: true
    },
    {
      name: 'channel',
      description: 'The channel to start the giveaway in',
      type: 'CHANNEL',
      required: true
    },
    {
      name: 'bonusrole',
      description: 'Role which would receive bonus entries',
      type: 'ROLE',
      required: false
    },
    {
      name: 'bonusamount',
      description: 'The amount of bonus entries the role will receive',
      type: 'INTEGER',
      required: false
    },
    {
      name: 'invite',
      description: 'Invite of the server you want to add as giveaway joining requirement',
      type: 'STRING',
      required: false
    },
    {
      name: 'role',
      description: 'Role you want to add as giveaway joining requirement',
      type: 'ROLE',
      required: false
    },
  ],

  run: async (client, interaction) => {
    // Check permissions
    if (!interaction.member.permissions.has(Permissions.FLAGS.MANAGE_MESSAGES) && 
        !interaction.member.roles.cache.some((r) => r.name === "Giveaways")) {
      return interaction.reply({
        content: ':x: You need to have the manage messages permissions to start giveaways.',
        ephemeral: true
      });
    }

    // Get and validate options
    const giveawayChannel = interaction.options.getChannel('channel');
    const giveawayDuration = interaction.options.getString('duration');
    const giveawayWinnerCount = interaction.options.getInteger('winners');
    const giveawayPrize = interaction.options.getString('prize');
    const bonusRole = interaction.options.getRole('bonusrole');
    const bonusEntries = interaction.options.getInteger('bonusamount');
    const roleReq = interaction.options.getRole('role');
    const invite = interaction.options.getString('invite');

    if (!giveawayChannel.isText()) {
      return interaction.reply({ content: ':x: Please select a text channel!', ephemeral: true });
    }

    const duration = ms(giveawayDuration);
    if (isNaN(duration)) {
      return interaction.reply({ content: ':x: Please select a valid duration!', ephemeral: true });
    }

    if (giveawayWinnerCount < 1) {
      return interaction.reply({ content: ':x: Please select a valid winner count! It must be greater than or equal to one.', ephemeral: true });
    }

    if (bonusRole && !bonusEntries) {
      return interaction.reply({
        content: `:x: You must specify how many bonus entries ${bonusRole} would receive!`,
        ephemeral: true
      });
    }

    await interaction.deferReply({ ephemeral: true });

    // Handle invite requirement
    let reqInvite;
    if (invite) {
      try {
        const inviteInfo = await client.fetchInvite(invite);
        const clientIsInServer = client.guilds.cache.has(inviteInfo.guild.id);
        if (!clientIsInServer) {
          return interaction.editReply({
            embeds: [createErrorEmbed(client, "I'm not in that server! Please invite me there to set it as a requirement.")]
          });
        }
        reqInvite = inviteInfo;
      } catch (error) {
        console.error("Error fetching invite:", error);
        return interaction.editReply({
          embeds: [createErrorEmbed(client, "Invalid invite link provided. Please check and try again.")]
        });
      }
    }

    // Set up giveaway data
    const giveawayData = {
      duration: duration,
      prize: giveawayPrize,
      winnerCount: giveawayWinnerCount,
      hostedBy: interaction.user,
      botsCanWin: false,
      messages: {
        giveaway: (client.config.everyoneMention ? "@everyone\n\n" : "") + "🎉 **GIVEAWAY** 🎉",
        giveawayEnded: (client.config.everyoneMention ? "@everyone\n\n" : "") + "🎉 **GIVEAWAY ENDED** 🎉",
        drawing: 'Ends: {timestamp}',
        dropMessage: "Be the first to react with 🎉 !",
        inviteToParticipate: "React with 🎉 to participate!",
        winMessage: "Congratulations, {winners}! You won **{this.prize}**!",
        embedFooter: "Giveaways",
        noWinner: "Giveaway cancelled, no valid participations.",
        hostedBy: "Hosted by: {this.hostedBy}",
        winners: "Winner(s): {winners}",
        endedAt: "Ended at"
      },
      lastChance: {
        enabled: true,
        content: '⚠️ **LAST CHANCE TO ENTER !** ⚠️',
        threshold: 5000,
        embedColor: '#FF0000'
      }
    };

    // Add bonus entries if applicable
    if (bonusRole && bonusEntries) {
      giveawayData.bonusEntries = [
        {
          bonus: (member) => member.roles.cache.has(bonusRole.id) ? bonusEntries : null,
          cumulative: false
        }
      ];
    }

    // Add extra data for role and server requirements
    giveawayData.extraData = {
      server: reqInvite ? reqInvite.guild.id : null,
      role: roleReq ? roleReq.id : null,
    };

    // Modify inviteToParticipate message based on requirements
    if (roleReq && !reqInvite) {
      giveawayData.messages.inviteToParticipate = `React with 🎉 to participate!\n>>> Only members with the ${roleReq} role can participate in this giveaway!`;
    } else if (roleReq && reqInvite) {
      giveawayData.messages.inviteToParticipate = `React with 🎉 to participate!\n>>> - Only members with the ${roleReq} role can participate in this giveaway!\n- Members must join [this server](${reqInvite}) to participate!`;
    } else if (!reqInvite && reqInvite) {
      giveawayData.messages.inviteToParticipate = `React with 🎉 to participate!\n>>> Members must join [this server](${reqInvite}) to participate in this giveaway!`;
    }

    // Start giveaway
    try {
      const giveaway = await client.giveawaysManager.start(giveawayChannel, giveawayData);

      // Add a reaction to the giveaway message
      await giveaway.message.react('🎉');

      await interaction.editReply({
        content: `Giveaway started in ${giveawayChannel}!`,
        ephemeral: true
      });

      if (bonusRole && bonusEntries) {
        const bonusEmbed = new MessageEmbed()
          .setAuthor({ name: `Bonus Entries Alert!` })
          .setDescription(`**${bonusRole}** has **${bonusEntries}** extra entries in this giveaway!`)
          .setColor("#2F3136")
          .setTimestamp();
        await giveawayChannel.send({ embeds: [bonusEmbed] });
      }
    } catch (error) {
      console.error("Error starting giveaway:", error);
      await interaction.editReply({
        content: 'An error occurred while starting the giveaway. Please try again.',
        ephemeral: true
      });q
    }
  }
  };

  function createErrorEmbed(client, message) {
  return new MessageEmbed()
    .setColor("#2F3136")
    .setAuthor({ name: client.user.username, iconURL: client.user.displayAvatarURL() })
    .setTitle("Error")
    .setDescription(message)
    .setTimestamp()
    .setFooter({ text: "Giveaway Bot", iconURL: client.user.displayAvatarURL() });
  }q
hey fix this FOR ME GIVEAWAY ISN'T ENDING HELP ME 
FAST MAKE MORE BETTER AND GIVE FULL CODE