#!/usr/bin/env node
/**
 * Create #staff-commands channel with command documentation
 * 
 * Created: April 8, 2026
 * Chronicler: #71
 */

require('dotenv').config({ path: '/opt/arbiter-3.0/.env' });
const { Client, GatewayIntentBits, ChannelType, EmbedBuilder } = require('discord.js');

async function main() {
  console.log('📋 Creating #staff-commands channel');
  console.log('====================================');

  const client = new Client({ 
    intents: [GatewayIntentBits.Guilds] 
  });

  try {
    await client.login(process.env.DISCORD_BOT_TOKEN);
    await new Promise(resolve => {
      if (client.isReady()) resolve();
      else client.once('ready', resolve);
    });
    console.log(`✅ Logged in as ${client.user.tag}`);

    const guild = client.guilds.cache.get(process.env.GUILD_ID);
    await guild.channels.fetch();
    console.log(`✅ Found guild: ${guild.name}`);

    // Find Staff Area category
    const staffCategory = guild.channels.cache.find(
      ch => ch.type === ChannelType.GuildCategory && ch.name.includes('Staff')
    );

    if (!staffCategory) {
      console.log('❌ Staff Area category not found!');
      return;
    }
    console.log(`✅ Found category: ${staffCategory.name}`);

    // Check if channel already exists
    const existingChannel = guild.channels.cache.find(
      ch => ch.name === 'staff-commands' && ch.parentId === staffCategory.id
    );

    if (existingChannel) {
      console.log('⚠️  #staff-commands already exists, posting documentation...');
      await postDocumentation(existingChannel);
      return;
    }

    // Create the channel
    const channel = await guild.channels.create({
      name: 'staff-commands',
      type: ChannelType.GuildText,
      parent: staffCategory.id,
      topic: 'Arbiter bot command reference for staff',
      reason: 'Staff command documentation - Chronicler #71'
    });
    console.log(`✅ Created: #${channel.name}`);

    // Post documentation
    await postDocumentation(channel);

    console.log('');
    console.log('✅ Done! Check #staff-commands in Discord.');

  } catch (error) {
    console.error('❌ ERROR:', error.message);
  } finally {
    client.destroy();
  }
}

async function postDocumentation(channel) {
  // Header message
  await channel.send({
    content: `# 🤖 Arbiter Bot Commands

This channel documents all slash commands available through The Arbiter. Commands are organized by who can use them.

---`
  });

  // /link command embed
  const linkEmbed = new EmbedBuilder()
    .setColor(0x4ECDC4) // Frost color
    .setTitle('📎 /link')
    .setDescription('Links a Discord account to a Minecraft username for automatic whitelist management.')
    .addFields(
      { 
        name: '👥 Who Can Use', 
        value: 'Everyone (all server members)', 
        inline: true 
      },
      { 
        name: '📍 Where to Use', 
        value: 'Any channel', 
        inline: true 
      },
      {
        name: '📝 Usage',
        value: '```/link username:YourMinecraftName```',
        inline: false
      },
      {
        name: '⚙️ What It Does',
        value: `1. Validates the Minecraft username exists via Mojang API
2. Stores the Discord ↔ Minecraft link in the database
3. Triggers an immediate whitelist sync across all servers
4. Player is automatically whitelisted on servers they have access to`,
        inline: false
      },
      {
        name: '💡 Notes',
        value: `• Username is case-sensitive (uses Mojang's official casing)
• Each Discord account can only link one Minecraft account
• Re-running the command updates the linked account
• Response is ephemeral (only visible to the user)`,
        inline: false
      }
    )
    .setFooter({ text: 'The Arbiter • Firefrost Gaming' });

  await channel.send({ embeds: [linkEmbed] });

  // /createserver command embed
  const createServerEmbed = new EmbedBuilder()
    .setColor(0xFF6B35) // Fire color
    .setTitle('🎮 /createserver')
    .setDescription('Creates a complete Discord server setup for a new Minecraft server with one command.')
    .addFields(
      { 
        name: '👥 Who Can Use', 
        value: 'Staff, Moderators, Trinity only', 
        inline: true 
      },
      { 
        name: '📍 Where to Use', 
        value: 'Any channel', 
        inline: true 
      },
      {
        name: '📝 Usage',
        value: '```/createserver name:Server Name```',
        inline: false
      },
      {
        name: '⚙️ What It Creates',
        value: `**Role:** \`Server Name\`

**Category:** \`🎮 Server Name\`

**Channels:**
• \`server-name-chat\` — General text chat
• \`server-name-in-game\` — In-game chat bridge
• \`server-name-forum\` — Discussion forum with tags
• \`Server Name\` — Voice channel

**Forum Tags:** Builds, Help, Suggestion, Bug Report, Achievement, Guide

**Welcome Post:** Auto-generated and archived`,
        inline: false
      },
      {
        name: '🔐 Permissions Applied',
        value: `• **@everyone** — Cannot see
• **Wanderer** — Can see, cannot interact (window shopping)
• **Server Role** — Full access
• **Staff/Mods/Trinity** — Full access`,
        inline: false
      },
      {
        name: '📋 After Running',
        value: `The bot will suggest an unused emoji. To complete setup:

1. Go to <#1403980899464384572>
2. Add the suggested emoji as a reaction
3. Configure Carl-bot to assign the new role when reacted`,
        inline: false
      },
      {
        name: '💡 Notes',
        value: `• Server name max 50 characters
• Cannot create if role or category already exists
• Channels are auto-positioned in the new category
• Welcome post is archived so forums collapse cleanly`,
        inline: false
      }
    )
    .setFooter({ text: 'The Arbiter • Firefrost Gaming' });

  await channel.send({ embeds: [createServerEmbed] });

  // Future commands placeholder
  await channel.send({
    content: `---

## 🔮 Future Commands

More commands coming soon! Check back here for updates.

*Last updated: April 8, 2026*`
  });

  console.log('✅ Posted command documentation');
}

main();
