#!/usr/bin/env node
/**
 * Quick Fix: Wold's Vaults
 * Using role ID directly since the apostrophe character is weird
 */

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

const STANDARD_FORUM_TAGS = [
  { name: 'Builds', emoji: '🏗️' },
  { name: 'Help', emoji: '❓' },
  { name: 'Suggestion', emoji: '💡' },
  { name: 'Bug Report', emoji: '🐛' },
  { name: 'Achievement', emoji: '🎉' },
  { name: 'Guide', emoji: '📖' }
];

// Using role ID directly!
const WOLDS_VAULTS_ROLE_ID = '1491029373640376330';

const SERVER = {
  name: "Wold's Vaults",
  welcomeTitle: "Welcome to Wold's Vaults!",
  welcomeBody: `🗄️ **Crack the vaults. Claim the treasure.**

A progression-focused pack centered around vault hunting. Gear up, dive in, and see what riches await those brave enough to face the challenges within.

**This forum is your space to:**
- 🏗️ Share your vault hauls
- ❓ Ask about vault strategies
- 💡 Suggest improvements
- 🎉 Celebrate legendary finds

---

**🎮 First Challenge: Your Best Vault Haul!**

What's the best thing you've pulled from a vault? Show us!`
};

const ADMIN_ROLES = ['Staff', '🛡️ Moderator', '👑 The Wizard', '💎 The Emissary', '✨ The Catalyst'];

function sleep(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

async function main() {
  console.log("🔧 Quick Fix: Wold's Vaults (using role ID)");
  console.log('=============================================');

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

  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();
    await guild.roles.fetch();

    // Get role by ID
    const serverRole = guild.roles.cache.get(WOLDS_VAULTS_ROLE_ID);
    if (!serverRole) {
      console.log(`❌ Role ID not found: ${WOLDS_VAULTS_ROLE_ID}`);
      return;
    }
    console.log(`✅ Found role: ${serverRole.name} (${serverRole.id})`);

    const everyoneRole = guild.roles.everyone;
    const wandererRole = guild.roles.cache.find(r => r.name === 'Wanderer');
    const adminRoleIds = ADMIN_ROLES.map(name => guild.roles.cache.find(r => r.name === name)?.id).filter(Boolean);

    const permissionOverwrites = [
      { id: everyoneRole.id, deny: [PermissionFlagsBits.ViewChannel, PermissionFlagsBits.SendMessages, PermissionFlagsBits.Connect] },
      { id: wandererRole.id, allow: [PermissionFlagsBits.ViewChannel], deny: [PermissionFlagsBits.SendMessages, PermissionFlagsBits.Connect] },
      { id: serverRole.id, allow: [PermissionFlagsBits.ViewChannel, PermissionFlagsBits.SendMessages, PermissionFlagsBits.Connect, PermissionFlagsBits.ReadMessageHistory] },
      ...adminRoleIds.map(roleId => ({
        id: roleId,
        allow: [PermissionFlagsBits.ViewChannel, PermissionFlagsBits.SendMessages, PermissionFlagsBits.Connect, PermissionFlagsBits.ReadMessageHistory]
      }))
    ];

    // Create category
    console.log(`Creating category: 🎮 ${SERVER.name}`);
    const category = await guild.channels.create({
      name: `🎮 ${SERVER.name}`,
      type: ChannelType.GuildCategory,
      permissionOverwrites,
      reason: 'Task #98 Fix - Chronicler #71'
    });
    console.log(`✅ Created category: ${category.id}`);
    await sleep(500);

    // Create chat
    const chat = await guild.channels.create({
      name: 'wolds-vaults-chat',
      type: ChannelType.GuildText,
      parent: category.id,
      reason: 'Task #98 Fix - Chronicler #71'
    });
    console.log(`✅ Created: ${chat.name}`);
    await sleep(500);

    // Create in-game
    const ingame = await guild.channels.create({
      name: 'wolds-vaults-in-game',
      type: ChannelType.GuildText,
      parent: category.id,
      reason: 'Task #98 Fix - Chronicler #71'
    });
    console.log(`✅ Created: ${ingame.name}`);
    await sleep(500);

    // Create forum
    const forum = await guild.channels.create({
      name: 'wolds-vaults-forum',
      type: ChannelType.GuildForum,
      parent: category.id,
      availableTags: STANDARD_FORUM_TAGS.map(tag => ({ name: tag.name, emoji: { name: tag.emoji } })),
      reason: 'Task #98 Fix - Chronicler #71'
    });
    console.log(`✅ Created forum: ${forum.name}`);
    await sleep(500);

    // Welcome post
    const welcomeThread = await forum.threads.create({
      name: SERVER.welcomeTitle,
      message: { content: SERVER.welcomeBody },
      reason: 'Task #98 Fix - Chronicler #71'
    });
    console.log(`✅ Posted welcome: ${welcomeThread.name}`);
    await sleep(500);

    // Create voice
    const voice = await guild.channels.create({
      name: "Wold's Vaults",
      type: ChannelType.GuildVoice,
      parent: category.id,
      reason: 'Task #98 Fix - Chronicler #71'
    });
    console.log(`✅ Created voice: ${voice.name}`);

    console.log('');
    console.log("🎉 Wold's Vaults — COMPLETE!");
    console.log('');
    console.log('📊 FINAL TOTALS:');
    console.log('   Categories: 11 (10 new + 1 archive)');
    console.log('   Forums: 15');
    console.log('   Text channels: 20');
    console.log('   Voice channels: 10');
    console.log('   Welcome posts: 15');
    console.log('   Total new channels: 46 ✅');

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

main();
