/**
 * Reaction role handling — #get-roles channel.
 * REQ-2026-04-15-reaction-roles (Chronicler #92)
 *
 * Three bot-owned messages. Each emoji maps to a Discord role ID. On add →
 * assign role. On remove → remove role. Silent-fail on lookup errors so a bad
 * reaction can never crash the gateway listener.
 */

const { logAction } = require('../services/discordActionLog');

// Keyed by message ID → { emoji (unicode or custom name) → role ID }
const REACTION_ROLE_MAP = {
  // Message 1 — Choose Your Path
  '1493930565395681402': {
    '🔥': '1482490890453782612',  // Fire Path
    '❄️': '1482491234378448946',  // Frost Path
  },
  // Message 2 — Notification Preferences
  '1493930595435286548': {
    '📢': '1491778391060381776',  // Announcements
    '🎉': '1491778662922457199',  // Events
    '🗒️': '1491778706312532171',  // Patch Notes
  },
  // Message 3 — Server Roles
  '1493930614066253908': {
    '🪨': '1491028769132253274',  // Stoneblock 4
    '🏝️': '1491028496284258304',  // All The Mods: To the Sky
    '🔴': '1491029000108380170',  // All The Mons
    '🧙': '1491029070190870548',  // Mythcraft 5
    '⚔️': '1491029454011629749',  // Otherworld [D&D]
    '🧟': '1491029615739801800',  // DeceasedCraft
    '🍽️': '1493352900997415134',  // Farm Crossing 6
    '🏡': '1491030015746510939',  // Homestead
    '🌌': '1491028885981102270',  // Society: Sunlit Valley
    '🌊': '1491029215963906149',  // Beyond Depth
    '☁️': '1491029284159094904',  // Beyond Ascension
    '🏆': '1491029373640376330',  // Wold's Vaults
    '🤿': '1491029708878647356',  // Submerged 2
    '🌙': '1491029870002569298',  // Cottage Witch
    '🌿': '1493924685170343978',  // vanilla
  }
};

async function resolveReaction(reaction) {
  if (reaction.partial) {
    try { await reaction.fetch(); } catch (e) {
      console.warn('[ReactionRoles] failed to fetch partial:', e.message);
      return null;
    }
  }
  const map = REACTION_ROLE_MAP[reaction.message.id];
  if (!map) return null;
  // Unicode emojis use .name; custom emojis fall back to id.
  const key = reaction.emoji.name;
  const roleId = map[key];
  if (!roleId) return null;
  return { roleId };
}

async function handleReactionAdd(reaction, user) {
  try {
    if (user.bot) return;
    const resolved = await resolveReaction(reaction);
    if (!resolved) return;
    const guild = reaction.message.guild;
    if (!guild) return;
    const member = await guild.members.fetch(user.id).catch(() => null);
    if (!member) return;
    let addErr = null;
    await member.roles.add(resolved.roleId).catch(err => {
      addErr = err.message;
      console.warn(`[ReactionRoles] add failed for ${user.username} → ${resolved.roleId}:`, addErr);
    });
    logAction('reaction_role_add', user.id, user.username,
      { roleId: resolved.roleId, emoji: reaction.emoji.name, messageId: reaction.message.id },
      !addErr, addErr);
    if (!addErr) console.log(`🎭 [ReactionRoles] +${resolved.roleId} → ${user.username}`);
  } catch (err) {
    console.error('[ReactionRoles] add handler error:', err.message);
  }
}

async function handleReactionRemove(reaction, user) {
  try {
    if (user.bot) return;
    const resolved = await resolveReaction(reaction);
    if (!resolved) return;
    const guild = reaction.message.guild;
    if (!guild) return;
    const member = await guild.members.fetch(user.id).catch(() => null);
    if (!member) return;
    let rmErr = null;
    await member.roles.remove(resolved.roleId).catch(err => {
      rmErr = err.message;
      console.warn(`[ReactionRoles] remove failed for ${user.username} → ${resolved.roleId}:`, rmErr);
    });
    logAction('reaction_role_remove', user.id, user.username,
      { roleId: resolved.roleId, emoji: reaction.emoji.name, messageId: reaction.message.id },
      !rmErr, rmErr);
    if (!rmErr) console.log(`🎭 [ReactionRoles] -${resolved.roleId} → ${user.username}`);
  } catch (err) {
    console.error('[ReactionRoles] remove handler error:', err.message);
  }
}

module.exports = { REACTION_ROLE_MAP, handleReactionAdd, handleReactionRemove };
