const { SlashCommandBuilder, EmbedBuilder } = require('discord.js');
const { getServerMode, getEmbedColor } = require('../utils/modeHelper');

module.exports = {
  data: new SlashCommandBuilder()
    .setName('roll')
    .setDescription('Roll dice')
    .addStringOption(option =>
      option.setName('dice')
        .setDescription('Dice notation (e.g., 2d6, d20, 3d8+5)')
        .setRequired(false)
    )
    .addIntegerOption(option =>
      option.setName('sides')
        .setDescription('Number of sides (default: 6)')
        .setRequired(false)
        .setMinValue(2)
        .setMaxValue(1000)
    )
    .addIntegerOption(option =>
      option.setName('count')
        .setDescription('Number of dice to roll (default: 1)')
        .setRequired(false)
        .setMinValue(1)
        .setMaxValue(100)
    ),

  async execute(interaction, supabase, client) {
    const diceNotation = interaction.options.getString('dice');
    let sides = interaction.options.getInteger('sides') || 6;
    let count = interaction.options.getInteger('count') || 1;
    let modifier = 0;

    if (diceNotation) {
      const match = diceNotation.match(/^(\d*)d(\d+)([+-]\d+)?$/i);
      if (match) {
        count = match[1] ? parseInt(match[1]) : 1;
        sides = parseInt(match[2]);
        modifier = match[3] ? parseInt(match[3]) : 0;
        
        if (count > 100) count = 100;
        if (sides > 1000) sides = 1000;
      } else {
        return interaction.reply({
          content: 'Invalid dice notation. Use format like `2d6`, `d20`, or `3d8+5`',
          ephemeral: true
        });
      }
    }

    const rolls = [];
    for (let i = 0; i < count; i++) {
      rolls.push(Math.floor(Math.random() * sides) + 1);
    }

    const sum = rolls.reduce((a, b) => a + b, 0);
    const total = sum + modifier;
    
    const mode = await getServerMode(supabase, interaction.guildId);

    const embed = new EmbedBuilder()
      .setColor(getEmbedColor(mode))
      .setTitle('🎲 Dice Roll')
      .setTimestamp()
      .setFooter({ text: `Rolled by ${interaction.user.username}` });

    if (count === 1 && modifier === 0) {
      embed.setDescription(`You rolled a **${total}**!`);
    } else {
      const rollsDisplay = rolls.length <= 20 
        ? rolls.map(r => `\`${r}\``).join(' + ')
        : `${rolls.slice(0, 20).map(r => `\`${r}\``).join(' + ')} ... (+${rolls.length - 20} more)`;
      
      let formula = `${count}d${sides}`;
      if (modifier > 0) formula += `+${modifier}`;
      else if (modifier < 0) formula += modifier;

      embed.addFields(
        { name: '🎯 Formula', value: formula, inline: true },
        { name: '📊 Total', value: `**${total}**`, inline: true }
      );
      
      if (rolls.length <= 20) {
        embed.addFields({ name: '🎲 Rolls', value: rollsDisplay });
      }
      
      if (modifier !== 0) {
        embed.addFields({ 
          name: '➕ Calculation', 
          value: `${sum} ${modifier >= 0 ? '+' : ''}${modifier} = **${total}**`,
          inline: true 
        });
      }
    }

    await interaction.reply({ embeds: [embed] });
  },
};
