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

module.exports = {
  data: new SlashCommandBuilder()
    .setName('gift')
    .setDescription('Gift XP to another user')
    .addUserOption(option =>
      option.setName('user')
        .setDescription('User to gift XP to')
        .setRequired(true)
    )
    .addIntegerOption(option =>
      option.setName('amount')
        .setDescription('Amount of XP to gift')
        .setRequired(true)
        .setMinValue(1)
        .setMaxValue(1000)
    ),

  async execute(interaction, supabase, client) {
    const recipient = interaction.options.getUser('user');
    const amount = interaction.options.getInteger('amount');
    const sender = interaction.user;
    const mode = await getServerMode(supabase, interaction.guildId);
    const guildId = interaction.guildId;

    if (recipient.id === sender.id) {
      return interaction.reply({ content: "You can't gift XP to yourself!", ephemeral: true });
    }

    if (recipient.bot) {
      return interaction.reply({ content: "You can't gift XP to bots!", ephemeral: true });
    }

    if (!supabase) {
      return interaction.reply({ content: 'Gift system unavailable.', ephemeral: true });
    }

    try {
      let senderXp = 0;

      if (mode === 'standalone') {
        const senderData = await getStandaloneXp(supabase, sender.id, guildId);
        senderXp = senderData?.xp || 0;
      } else {
        const { data } = await supabase
          .from('user_profiles')
          .select('xp')
          .eq('discord_id', sender.id)
          .maybeSingle();
        senderXp = data?.xp || 0;
      }

      if (senderXp < amount) {
        return interaction.reply({
          content: `You don't have enough XP! You have ${senderXp} XP.`,
          ephemeral: true
        });
      }

      if (mode === 'standalone') {
        await updateStandaloneXp(supabase, sender.id, guildId, -amount, sender.username);
        await updateStandaloneXp(supabase, recipient.id, guildId, amount, recipient.username);
      } else {
        await supabase
          .from('user_profiles')
          .update({ xp: senderXp - amount })
          .eq('discord_id', sender.id);

        const { data: recipientData } = await supabase
          .from('user_profiles')
          .select('xp')
          .eq('discord_id', recipient.id)
          .maybeSingle();

        if (recipientData) {
          await supabase
            .from('user_profiles')
            .update({ xp: (recipientData.xp || 0) + amount })
            .eq('discord_id', recipient.id);
        }
      }

      const embed = new EmbedBuilder()
        .setColor(EMBED_COLORS.success)
        .setTitle('🎁 Gift Sent!')
        .setDescription(`${sender} gifted **${amount} XP** to ${recipient}!`)
        .setThumbnail(recipient.displayAvatarURL({ size: 128 }))
        .setTimestamp();

      await interaction.reply({ embeds: [embed] });
    } catch (e) {
      await interaction.reply({ content: 'Failed to send gift.', ephemeral: true });
    }
  },
};
