/**
 * Discord Role Sync Service
 * Handles adding/removing Discord roles based on subscription tier
 * 
 * Task #87: Arbiter Lifecycle Handlers
 * Date: April 6, 2026
 */

const { getRoleMappings } = require('../utils/roleMappings');

// Tier level to role key mapping
const TIER_TO_ROLE_KEY = {
  1: 'the-awakened',
  2: 'fire-elemental',
  3: 'frost-elemental',
  4: 'fire-knight',
  5: 'frost-knight',
  6: 'fire-master',
  7: 'frost-master',
  8: 'fire-legend',
  9: 'frost-legend',
  10: 'the-sovereign'
};

// All subscriber role keys (for removal)
const ALL_SUBSCRIBER_ROLE_KEYS = Object.values(TIER_TO_ROLE_KEY);

// Store Discord client reference
let discordClient = null;

/**
 * Initialize the service with Discord client
 * Called from index.js after client is ready
 */
function init(client) {
  discordClient = client;
  console.log('✅ Discord Role Sync service initialized');
}

/**
 * Get the Discord client
 */
function getClient() {
  return discordClient;
}

/**
 * Sync Discord role for a user based on their tier
 * Removes old tier roles and adds the new one
 * 
 * @param {string} discordId - User's Discord ID
 * @param {number} newTierLevel - New tier level (1-10), or null for complete removal
 * @returns {Promise<{success: boolean, message: string}>}
 */
async function syncRole(discordId, newTierLevel) {
  if (!discordClient) {
    return { success: false, message: 'Discord client not initialized' };
  }

  const guildId = process.env.GUILD_ID;
  if (!guildId) {
    return { success: false, message: 'GUILD_ID not configured' };
  }

  try {
    const guild = discordClient.guilds.cache.get(guildId);
    if (!guild) {
      return { success: false, message: 'Guild not found in cache' };
    }

    const member = await guild.members.fetch(discordId).catch(() => null);
    if (!member) {
      return { success: false, message: 'Member not found in guild (may have left)' };
    }

    const roleMappings = getRoleMappings();
    
    // Get all role IDs to remove
    const rolesToRemove = ALL_SUBSCRIBER_ROLE_KEYS
      .map(key => roleMappings[key])
      .filter(id => id && member.roles.cache.has(id));

    // Remove old roles
    if (rolesToRemove.length > 0) {
      await member.roles.remove(rolesToRemove);
    }

    // Add new role if tier specified
    if (newTierLevel !== null) {
      const newRoleKey = TIER_TO_ROLE_KEY[newTierLevel];
      const newRoleId = roleMappings[newRoleKey];
      
      if (newRoleId) {
        await member.roles.add(newRoleId);
        return { 
          success: true, 
          message: `Synced to tier ${newTierLevel} (${newRoleKey})` 
        };
      } else {
        return { 
          success: false, 
          message: `No role mapping found for tier ${newTierLevel}` 
        };
      }
    }

    return { success: true, message: 'All subscriber roles removed' };

  } catch (error) {
    console.error('Discord role sync error:', error);
    return { success: false, message: error.message };
  }
}

/**
 * Remove all subscriber roles from a user (for bans/chargebacks)
 * 
 * @param {string} discordId - User's Discord ID
 * @returns {Promise<{success: boolean, message: string}>}
 */
async function removeAllRoles(discordId) {
  return syncRole(discordId, null);
}

/**
 * Downgrade user to Awakened tier
 * Used when grace period expires
 * 
 * @param {string} discordId - User's Discord ID
 * @returns {Promise<{success: boolean, message: string}>}
 */
async function downgradeToAwakened(discordId) {
  return syncRole(discordId, 1); // Tier 1 = Awakened
}

module.exports = {
  init,
  getClient,
  syncRole,
  removeAllRoles,
  downgradeToAwakened,
  TIER_TO_ROLE_KEY,
  ALL_SUBSCRIBER_ROLE_KEYS
};
