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

const repCooldowns = new Map();
const REP_COOLDOWN = 12 * 60 * 60 * 1000;

module.exports = {
  data: new SlashCommandBuilder()
    .setName('rep')
    .setDescription('Give a reputation point to someone')
    .addUserOption(option =>
      option.setName('user')
        .setDescription('The user to give rep to')
        .setRequired(true)
    )
    .addStringOption(option =>
      option.setName('reason')
        .setDescription('Why are you giving them rep?')
        .setRequired(false)
        .setMaxLength(200)
    ),

  async execute(interaction, supabase, client) {
    const targetUser = interaction.options.getUser('user');
    const reason = interaction.options.getString('reason');
    const userId = interaction.user.id;
    const guildId = interaction.guildId;
    const mode = await getServerMode(supabase, interaction.guildId);

    if (targetUser.id === userId) {
      return interaction.reply({
        content: "You can't give rep to yourself!",
        ephemeral: true
      });
    }

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

    const cooldownKey = `${guildId}-${userId}`;
    const lastRep = repCooldowns.get(cooldownKey);
    if (lastRep && Date.now() - lastRep < REP_COOLDOWN) {
      const remaining = REP_COOLDOWN - (Date.now() - lastRep);
      const hours = Math.floor(remaining / (60 * 60 * 1000));
      const minutes = Math.floor((remaining % (60 * 60 * 1000)) / (60 * 1000));
      return interaction.reply({
        content: `You can give rep again in ${hours}h ${minutes}m.`,
        ephemeral: true
      });
    }

    repCooldowns.set(cooldownKey, Date.now());

    if (supabase) {
      try {
        await supabase.from('reputation').insert({
          guild_id: guildId,
          giver_id: userId,
          receiver_id: targetUser.id,
          reason: reason,
          created_at: new Date().toISOString()
        });
      } catch (e) {}
    }

    const embed = new EmbedBuilder()
      .setColor(EMBED_COLORS.success)
      .setTitle('⭐ Reputation Given!')
      .setDescription(`${interaction.user} gave a rep point to ${targetUser}!`)
      .setThumbnail(targetUser.displayAvatarURL({ size: 128 }))
      .setTimestamp();

    if (reason) {
      embed.addFields({ name: '💬 Reason', value: reason });
    }

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