#!/usr/bin/env node
/**
 * Quick Fix: Wold's Vaults
 * The role uses a curly apostrophe ('), not straight (')
 */

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: '📖' }
];

const SERVER = {
  name: "Wold's Vaults",
  roleName: "Wold's Vaults",  // Curly apostrophe!
  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 slugify(name) {
  return name.toLowerCase().replace(/[^a-z0-9\s-]/g, '').replace(/\s+/g, '-').substring(0, 100);
}

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

async function main() {
  console.log("🔧 Quick Fix: Wold's Vaults");
  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();

    // Find role with curly apostrophe
    const serverRole = guild.roles.cache.find(r => r.name === SERVER.roleName);
    if (!serverRole) {
      console.log(`❌ Role still not found: ${SERVER.roleName}`);
      console.log('Available roles with "Wold":');
      guild.roles.cache.filter(r => r.name.toLowerCase().includes('wold')).forEach(r => {
        console.log(`   "${r.name}" (${r.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: `${slugify(SERVER.name)}-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: `${slugify(SERVER.name)}-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: `${slugify(SERVER.name)}-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: SERVER.name,
      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!");

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

main();
