const { handleLinkCommand } = require('./commands');
const { handleCreateServerCommand } = require('./createserver');
const { handleDelServerCommand } = require('./delserver');
const { handleTasksCommand, handleTaskButton } = require('./tasks');
const { handleVerifyMvcCommand } = require('./verifymvc');
const { handleReactionAdd, handleReactionRemove } = require('./reactionRoles');
const discordRoleSync = require('../services/discordRoleSync');
const { logAction } = require('../services/discordActionLog');

// Carl-bot migration: Wanderer role assigned to every new join.
const WANDERER_ROLE_ID = '1487267974367805545';

const WELCOME_DM = (username) =>
  `Hey ${username}! Welcome to Firefrost Gaming!\n` +
  `You just landed as a Wanderer — the door is open, come explore!\n\n` +
  `Quick links:\n` +
  `• Check out #rules first\n` +
  `• Say hi in #introductions\n` +
  `• Head to #get-roles to pick your path and grab your server channels\n\n` +
  `Questions? We're here. Welcome to the family!`;

function registerEvents(client) {
  client.on('interactionCreate', async interaction => {
    // Button interactions
    if (interaction.isButton()) {
      if (interaction.customId.startsWith('task_')) {
        await handleTaskButton(interaction);
      }
      return;
    }

    if (!interaction.isChatInputCommand()) return;
    if (interaction.commandName === 'link') {
      await handleLinkCommand(interaction);
    }
    if (interaction.commandName === 'createserver') {
      await handleCreateServerCommand(interaction);
    }
    if (interaction.commandName === 'delserver') {
      await handleDelServerCommand(interaction);
    }
    if (interaction.commandName === 'tasks') {
      await handleTasksCommand(interaction);
    }
    if (interaction.commandName === 'verify-mvc') {
      await handleVerifyMvcCommand(interaction);
    }
  });

  // Reaction roles — #get-roles channel
  client.on('messageReactionAdd', (reaction, user) => {
    handleReactionAdd(reaction, user).catch(err =>
      console.error('[events] reaction add error:', err.message)
    );
  });
  client.on('messageReactionRemove', (reaction, user) => {
    handleReactionRemove(reaction, user).catch(err =>
      console.error('[events] reaction remove error:', err.message)
    );
  });

  // Carl-bot migration — new member onboarding
  client.on('guildMemberAdd', async (member) => {
    try {
      let wandererErr = null;
      await member.roles.add(WANDERER_ROLE_ID).catch(err => {
        wandererErr = err.message;
        console.warn(`[Welcome] failed to add Wanderer to ${member.user.username}:`, wandererErr);
      });
      logAction('wanderer_assigned', member.user.id, member.user.username,
        { roleId: WANDERER_ROLE_ID }, !wandererErr, wandererErr);
      if (!wandererErr) console.log(`👋 [Welcome] ${member.user.username} joined → Wanderer`);

      // DM welcome (silent-fail if user has DMs closed)
      let dmErr = null;
      try {
        await member.send(WELCOME_DM(member.user.username));
      } catch (err) {
        dmErr = err.message;
        console.log(`[Welcome] DM to ${member.user.username} skipped: ${dmErr}`);
      }
      logAction('welcome_dm', member.user.id, member.user.username,
        {}, !dmErr, dmErr);
    } catch (err) {
      console.error('[Welcome] guildMemberAdd error:', err.message);
    }
  });

  client.on('ready', () => {
    console.log(`Discord bot logged in as ${client.user.tag}`);
    // Initialize role sync service with the ready client
    discordRoleSync.init(client);
  });
}

module.exports = { registerEvents };
