/**
 * Simple Discord Reaction Role Bot
 * Monitors a specific message for reactions and assigns roles
 */

const { Client, GatewayIntentBits, Partials } = require('discord.js');

// Configuration
const CONFIG = {
  token: process.env.DISCORD_BOT_TOKEN || 'MTQ1ODIzNDU5MzcxNDExNDY0MA.GmFROz.V8GyvBWFD9LtpOWtOIUxHRDfyoPHQJU4XKXDWc',
  guildId: '1449158500344270961',
  messageId: '1464871902777708637', // Welcome message with reactions
  channelId: '1464535949798150250', // #welcome
  
  // Emoji to Role mappings
  emojiRoles: {
    '🔧': '1464871798116974703', // Builder
    '🎵': '1464871799970861057', // Producer
    '📈': '1464871801002786827', // Marketer
    '🏢': '1464871802173001780', // Operator
    '📰': '1464871803418705970', // Feed Subscriber
  }
};

const client = new Client({
  intents: [
    GatewayIntentBits.Guilds,
    GatewayIntentBits.GuildMembers,
    GatewayIntentBits.GuildMessageReactions,
  ],
  partials: [Partials.Message, Partials.Reaction, Partials.User],
});

client.once('ready', () => {
  console.log(`✅ Reaction Role Bot logged in as ${client.user.tag}`);
  console.log(`📍 Watching message ${CONFIG.messageId} in channel ${CONFIG.channelId}`);
  console.log(`🎯 Emoji-Role mappings:`, CONFIG.emojiRoles);
});

// Handle reaction add
client.on('messageReactionAdd', async (reaction, user) => {
  // Ignore bot reactions
  if (user.bot) return;
  
  // Fetch partial if needed
  if (reaction.partial) {
    try {
      await reaction.fetch();
    } catch (error) {
      console.error('Error fetching reaction:', error);
      return;
    }
  }
  
  // Check if this is our tracked message
  if (reaction.message.id !== CONFIG.messageId) return;
  
  const emoji = reaction.emoji.name;
  const roleId = CONFIG.emojiRoles[emoji];
  
  if (!roleId) {
    console.log(`Unknown emoji: ${emoji}`);
    return;
  }
  
  try {
    const guild = await client.guilds.fetch(CONFIG.guildId);
    const member = await guild.members.fetch(user.id);
    await member.roles.add(roleId);
    console.log(`✅ Added role ${roleId} to ${user.tag} (reacted with ${emoji})`);
  } catch (error) {
    console.error(`Error adding role:`, error);
  }
});

// Handle reaction remove
client.on('messageReactionRemove', async (reaction, user) => {
  // Ignore bot reactions
  if (user.bot) return;
  
  // Fetch partial if needed
  if (reaction.partial) {
    try {
      await reaction.fetch();
    } catch (error) {
      console.error('Error fetching reaction:', error);
      return;
    }
  }
  
  // Check if this is our tracked message
  if (reaction.message.id !== CONFIG.messageId) return;
  
  const emoji = reaction.emoji.name;
  const roleId = CONFIG.emojiRoles[emoji];
  
  if (!roleId) return;
  
  try {
    const guild = await client.guilds.fetch(CONFIG.guildId);
    const member = await guild.members.fetch(user.id);
    await member.roles.remove(roleId);
    console.log(`❌ Removed role ${roleId} from ${user.tag} (unreacted ${emoji})`);
  } catch (error) {
    console.error(`Error removing role:`, error);
  }
});

// Login
client.login(CONFIG.token);
