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

const JOBS = [
  { name: 'Developer', emoji: '💻', minXp: 15, maxXp: 35, message: 'You wrote some clean code' },
  { name: 'Designer', emoji: '🎨', minXp: 12, maxXp: 30, message: 'You created a beautiful design' },
  { name: 'Writer', emoji: '✍️', minXp: 10, maxXp: 25, message: 'You wrote an engaging article' },
  { name: 'Streamer', emoji: '📺', minXp: 18, maxXp: 40, message: 'Your stream was a hit' },
  { name: 'Chef', emoji: '👨‍🍳', minXp: 8, maxXp: 22, message: 'You cooked a delicious meal' },
  { name: 'Teacher', emoji: '👨‍🏫', minXp: 12, maxXp: 28, message: 'You helped students learn' },
  { name: 'Artist', emoji: '🖼️', minXp: 14, maxXp: 32, message: 'You created a masterpiece' },
  { name: 'Musician', emoji: '🎵', minXp: 10, maxXp: 26, message: 'You performed an amazing song' },
  { name: 'Photographer', emoji: '📷', minXp: 11, maxXp: 24, message: 'You captured a perfect shot' },
  { name: 'YouTuber', emoji: '🎬', minXp: 16, maxXp: 38, message: 'Your video went viral' },
];

const workCooldowns = new Map();
const COOLDOWN = 60 * 60 * 1000;

module.exports = {
  data: new SlashCommandBuilder()
    .setName('work')
    .setDescription('Work to earn some XP!'),

  async execute(interaction, supabase, client) {
    const userId = interaction.user.id;
    const guildId = interaction.guildId;
    const mode = await getServerMode(supabase, interaction.guildId);

    const cooldownKey = `${guildId}-${userId}`;
    const lastWork = workCooldowns.get(cooldownKey);
    if (lastWork && Date.now() - lastWork < COOLDOWN) {
      const remaining = COOLDOWN - (Date.now() - lastWork);
      const minutes = Math.floor(remaining / 60000);
      const seconds = Math.floor((remaining % 60000) / 1000);
      return interaction.reply({
        content: `You're tired! You can work again in ${minutes}m ${seconds}s.`,
        ephemeral: true
      });
    }

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

    const job = JOBS[Math.floor(Math.random() * JOBS.length)];
    const xpEarned = Math.floor(Math.random() * (job.maxXp - job.minXp + 1)) + job.minXp;

    if (mode === 'standalone') {
      await updateStandaloneXp(supabase, userId, guildId, xpEarned, interaction.user.username);
    } else if (supabase) {
      try {
        const { data: profile } = await supabase
          .from('user_profiles')
          .select('xp')
          .eq('discord_id', userId)
          .maybeSingle();
        
        if (profile) {
          await supabase
            .from('user_profiles')
            .update({ xp: (profile.xp || 0) + xpEarned })
            .eq('discord_id', userId);
        }
      } catch (e) {}
    }

    const embed = new EmbedBuilder()
      .setColor(EMBED_COLORS.success)
      .setTitle(`${job.emoji} ${job.name}`)
      .setDescription(`${job.message} and earned **${xpEarned} XP**!`)
      .setFooter({ text: `${interaction.user.username} | Work again in 1 hour` })
      .setTimestamp();

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