#!/usr/bin/env node
/**
 * Discord Channel Creation Test Script
 * Phase 1: Create ONE test category with ONE forum channel
 * 
 * Purpose: Verify our channel creation approach works before running full script
 * 
 * Created: April 8, 2026
 * Chronicler: #71
 */

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

// ============================================================================
// CONFIGURATION
// ============================================================================

const DRY_RUN = false;  // Set to false to actually create channels

const TEST_CATEGORY_NAME = '🧪 Test Category';
const TEST_FORUM_NAME = 'test-forum';
const TEST_FORUM_TOPIC = 'Testing forum creation - safe to delete';

// Forum tags we'll use on all server forums
const STANDARD_FORUM_TAGS = [
  { name: 'Builds', emoji: '🏗️' },
  { name: 'Help', emoji: '❓' },
  { name: 'Suggestion', emoji: '💡' },
  { name: 'Bug Report', emoji: '🐛' },
  { name: 'Achievement', emoji: '🎉' },
  { name: 'Guide', emoji: '📖' }
];

// ============================================================================
// MAIN SCRIPT
// ============================================================================

async function main() {
  console.log('🔧 Discord Channel Creation Test');
  console.log('================================');
  console.log(`Mode: ${DRY_RUN ? '🔍 DRY RUN (no changes)' : '⚡ LIVE (will create channels)'}`);
  console.log('');

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

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

    // Get guild
    const guildId = process.env.GUILD_ID;
    const guild = client.guilds.cache.get(guildId);
    
    if (!guild) {
      throw new Error(`Guild ${guildId} not found. Is the bot in the server?`);
    }
    console.log(`✅ Found guild: ${guild.name}`);

    // Check bot permissions
    const botMember = guild.members.cache.get(client.user.id);
    if (!botMember) {
      await guild.members.fetch(client.user.id);
    }
    
    const permissions = guild.members.cache.get(client.user.id)?.permissions;
    console.log('');
    console.log('🔐 Bot Permissions Check:');
    console.log(`   Manage Channels: ${permissions?.has(PermissionFlagsBits.ManageChannels) ? '✅' : '❌'}`);
    console.log(`   Manage Roles: ${permissions?.has(PermissionFlagsBits.ManageRoles) ? '✅' : '❌'}`);
    console.log(`   Send Messages: ${permissions?.has(PermissionFlagsBits.SendMessages) ? '✅' : '❌'}`);
    console.log(`   Create Public Threads: ${permissions?.has(PermissionFlagsBits.CreatePublicThreads) ? '✅' : '❌'}`);
    
    if (!permissions?.has(PermissionFlagsBits.ManageChannels)) {
      throw new Error('Bot lacks Manage Channels permission!');
    }

    // Fetch existing channels
    await guild.channels.fetch();
    console.log('');
    console.log(`📊 Current channel count: ${guild.channels.cache.size}`);

    // Check if test category already exists
    const existingCategory = guild.channels.cache.find(
      ch => ch.type === ChannelType.GuildCategory && ch.name === TEST_CATEGORY_NAME
    );
    
    if (existingCategory) {
      console.log(`⚠️  Test category "${TEST_CATEGORY_NAME}" already exists (ID: ${existingCategory.id})`);
      console.log('   Delete it manually if you want to re-run this test.');
      
      // Check for forum in that category
      const existingForum = guild.channels.cache.find(
        ch => ch.type === ChannelType.GuildForum && ch.parentId === existingCategory.id
      );
      if (existingForum) {
        console.log(`   Forum "${existingForum.name}" exists in category (ID: ${existingForum.id})`);
      }
      
      client.destroy();
      return;
    }

    if (DRY_RUN) {
      console.log('');
      console.log('📋 DRY RUN - Would create:');
      console.log(`   1. Category: "${TEST_CATEGORY_NAME}"`);
      console.log(`   2. Forum: "${TEST_FORUM_NAME}" with ${STANDARD_FORUM_TAGS.length} tags`);
      console.log('');
      console.log('Set DRY_RUN = false to create these channels.');
      client.destroy();
      return;
    }

    // ========================================================================
    // LIVE MODE - CREATE CHANNELS
    // ========================================================================

    console.log('');
    console.log('🚀 Creating test channels...');

    // Step 1: Create category
    console.log(`   Creating category: ${TEST_CATEGORY_NAME}`);
    const category = await guild.channels.create({
      name: TEST_CATEGORY_NAME,
      type: ChannelType.GuildCategory,
      reason: 'Test by Chronicler #71 - Discord channel automation'
    });
    console.log(`   ✅ Category created: ${category.id}`);

    // Step 2: Create forum channel
    console.log(`   Creating forum: ${TEST_FORUM_NAME}`);
    const forum = await guild.channels.create({
      name: TEST_FORUM_NAME,
      type: ChannelType.GuildForum,
      parent: category.id,
      topic: TEST_FORUM_TOPIC,
      availableTags: STANDARD_FORUM_TAGS.map(tag => ({
        name: tag.name,
        emoji: tag.emoji ? { name: tag.emoji } : null
      })),
      reason: 'Test by Chronicler #71 - Discord channel automation'
    });
    console.log(`   ✅ Forum created: ${forum.id}`);

    // Step 3: Create a test welcome post in the forum
    console.log('   Creating welcome post in forum...');
    const welcomeThread = await forum.threads.create({
      name: '👋 Welcome to the Test Forum!',
      message: {
        content: `**This is a test welcome post.**\n\nIf you can see this, forum creation is working!\n\n🏗️ **Tags available:** ${STANDARD_FORUM_TAGS.map(t => t.name).join(', ')}\n\n*Created by Chronicler #71*`
      },
      reason: 'Test welcome post by Chronicler #71'
    });
    console.log(`   ✅ Welcome post created: ${welcomeThread.id}`);

    // Summary
    console.log('');
    console.log('✅ TEST COMPLETE!');
    console.log('================');
    console.log(`Category: ${category.name} (${category.id})`);
    console.log(`Forum: ${forum.name} (${forum.id})`);
    console.log(`Welcome Post: ${welcomeThread.name} (${welcomeThread.id})`);
    console.log('');
    console.log('👀 Check Discord to verify:');
    console.log('   1. Category appears with 🧪 emoji');
    console.log('   2. Forum is inside the category');
    console.log('   3. Forum has 6 tags (Builds, Help, Suggestion, Bug Report, Achievement, Guide)');
    console.log('   4. Welcome post is visible in the forum');
    console.log('');
    console.log('🗑️  When done testing, delete the category from Discord.');

  } catch (error) {
    console.error('');
    console.error('❌ ERROR:', error.message);
    if (error.code) {
      console.error('   Discord Error Code:', error.code);
    }
    if (error.rawError) {
      console.error('   Raw Error:', JSON.stringify(error.rawError, null, 2));
    }
  } finally {
    client.destroy();
    console.log('');
    console.log('👋 Disconnected from Discord.');
  }
}

main();
