import 'dotenv/config';
import { Client, GatewayIntentBits, Partials, Collection } from 'discord.js';
import { initDB } from './core/db.js';
import { loadCommands, loadEvents } from './core/loader.js';
import { startWebServer } from './web/server.js';
import { startScheduler } from './modules/automation/scheduler.js';

const client = new Client({
  intents: [
    GatewayIntentBits.Guilds,
    GatewayIntentBits.GuildMembers,
    GatewayIntentBits.GuildMessages,
    GatewayIntentBits.GuildMessageReactions,
    GatewayIntentBits.MessageContent,
    GatewayIntentBits.GuildEmojisAndStickers,
    GatewayIntentBits.GuildVoiceStates,
  ],
  partials: [Partials.Channel, Partials.Message, Partials.Reaction],
});

client.commands = new Collection();
client.cooldowns = new Collection();

await initDB();
await loadCommands(client);
await loadEvents(client);

if (!process.env.DISCORD_TOKEN) {
  console.error('❌ DISCORD_TOKEN missing in .env');
  process.exit(1);
}

await client.login(process.env.DISCORD_TOKEN);

// Side services (web dashboard, payment webhook, scheduler)
startWebServer(client);
startScheduler(client);

// Restore per-user bots yang sebelumnya 'running' (multi-tenant)
import('./core/bot-manager.js').then(m => m.restoreUserBots()).catch(e => console.error('[botmgr] restore failed:', e.message));

process.on('unhandledRejection', (err) => console.error('UnhandledRejection:', err));
process.on('uncaughtException', (err) => console.error('UncaughtException:', err));
