#!/usr/bin/env node
/**
 * Archive Welcome Posts
 * Archives all welcome threads in forum channels so they don't
 * keep forums "active" when categories are collapsed
 * 
 * Created: April 8, 2026
 * Chronicler: #71
 */

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

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

async function main() {
  console.log('📦 Archive Welcome Posts');
  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}`);
    console.log('');

    // Find all forum channels
    const forums = guild.channels.cache.filter(ch => ch.type === ChannelType.GuildForum);
    console.log(`Found ${forums.size} forum channels`);
    console.log('');

    let archived = 0;
    let alreadyArchived = 0;
    let errors = 0;

    for (const [id, forum] of forums) {
      // Skip if not a server forum (check for 🎮 parent or server-related name)
      const parent = forum.parent;
      if (!parent || !parent.name.includes('🎮')) {
        continue;
      }

      console.log(`📁 ${forum.name}`);

      // Fetch active threads
      const activeThreads = await forum.threads.fetchActive();
      
      for (const [threadId, thread] of activeThreads.threads) {
        // Look for welcome posts
        if (thread.name.toLowerCase().includes('welcome')) {
          if (thread.archived) {
            console.log(`   ⏭️  Already archived: ${thread.name}`);
            alreadyArchived++;
          } else {
            try {
              await thread.setArchived(true, 'Archiving welcome post - Chronicler #71');
              console.log(`   ✅ Archived: ${thread.name}`);
              archived++;
              await sleep(300);
            } catch (err) {
              console.log(`   ❌ Failed to archive: ${thread.name} - ${err.message}`);
              errors++;
            }
          }
        }
      }
    }

    console.log('');
    console.log('📊 SUMMARY');
    console.log('==========');
    console.log(`Archived:         ${archived}`);
    console.log(`Already archived: ${alreadyArchived}`);
    console.log(`Errors:           ${errors}`);
    console.log('');
    console.log('✅ Done! Categories should now collapse cleanly.');

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

main();
