const { SlashCommandBuilder, EmbedBuilder, PermissionFlagsBits } = require('discord.js');

module.exports = {
  data: new SlashCommandBuilder()
    .setName('federation')
    .setDescription('Manage cross-server role synchronization')
    .setDefaultMemberPermissions(PermissionFlagsBits.ManageRoles)
    .addSubcommand(subcommand =>
      subcommand
        .setName('link')
        .setDescription('Link a role for cross-server sync')
        .addRoleOption(option =>
          option.setName('role')
            .setDescription('Role to sync across servers')
            .setRequired(true)
        )
    )
    .addSubcommand(subcommand =>
      subcommand
        .setName('unlink')
        .setDescription('Remove a role from sync')
        .addRoleOption(option =>
          option.setName('role')
            .setDescription('Role to remove from sync')
            .setRequired(true)
        )
    )
    .addSubcommand(subcommand =>
      subcommand
        .setName('list')
        .setDescription('List all linked roles')
    ),
  
  async execute(interaction, supabase, client) {
    const subcommand = interaction.options.getSubcommand();
    
    if (subcommand === 'link') {
      const role = interaction.options.getRole('role');
      
      const mappingData = {
        name: role.name,
        guildId: interaction.guildId,
        guildName: interaction.guild.name,
        linkedAt: Date.now(),
      };
      client.federationMappings.set(role.id, mappingData);
      
      if (client.saveFederationMapping) {
        await client.saveFederationMapping(role.id, mappingData);
      }
      
      const embed = new EmbedBuilder()
        .setColor(0x00ff00)
        .setTitle('Role Linked')
        .setDescription(`${role} is now linked for federation sync.`)
        .addFields(
          { name: 'Role ID', value: role.id, inline: true },
          { name: 'Server', value: interaction.guild.name, inline: true }
        )
        .setTimestamp();
      
      await interaction.reply({ embeds: [embed] });
    }
    
    if (subcommand === 'unlink') {
      const role = interaction.options.getRole('role');
      
      if (client.federationMappings.has(role.id)) {
        client.federationMappings.delete(role.id);
        
        if (client.deleteFederationMapping) {
          await client.deleteFederationMapping(role.id);
        }
        
        const embed = new EmbedBuilder()
          .setColor(0xff6600)
          .setTitle('Role Unlinked')
          .setDescription(`${role} has been removed from federation sync.`)
          .setTimestamp();
        
        await interaction.reply({ embeds: [embed] });
      } else {
        const embed = new EmbedBuilder()
          .setColor(0xff0000)
          .setTitle('Not Found')
          .setDescription(`${role} is not currently linked.`)
          .setTimestamp();
        
        await interaction.reply({ embeds: [embed], ephemeral: true });
      }
    }
    
    if (subcommand === 'list') {
      const mappings = [...client.federationMappings.entries()];
      
      if (mappings.length === 0) {
        const embed = new EmbedBuilder()
          .setColor(0x7c3aed)
          .setTitle('Federation Roles')
          .setDescription('No roles are currently linked for federation sync.\nUse `/federation link` to add roles.')
          .setTimestamp();
        
        await interaction.reply({ embeds: [embed] });
        return;
      }
      
      const roleList = mappings.map(([roleId, data]) => 
        `<@&${roleId}> - ${data.guildName}`
      ).join('\n');
      
      const embed = new EmbedBuilder()
        .setColor(0x7c3aed)
        .setTitle('Federation Roles')
        .setDescription(roleList)
        .setFooter({ text: `${mappings.length} role(s) linked` })
        .setTimestamp();
      
      await interaction.reply({ embeds: [embed] });
    }
  },
};
