import { ActivityType, Client } from 'discord.js';
import { EventHandler } from '../utils/types';
import { logger } from '../utils/logger';
import { env } from '../config/env';
import { context } from '../config/context';
import { settingsStore } from '../config/state';

const event: EventHandler = {
  name: 'ready',
  once: true,
  async execute(client: Client) {
    try {
      logger.info(`Bot eingeloggt als ${client.user?.tag}`);
      const website = env.publicBaseUrl || 'https://papo.gg';
      const activities = [
        { name: 'Papo | /help', type: ActivityType.Playing },
        { name: `Dashboard: ${website}`, type: ActivityType.Watching },
        { name: `${client.guilds.cache.size} Guilds verwaltet`, type: ActivityType.Watching }
      ];
      let idx = 0;
      const applyPresence = () => {
        const activity = activities[idx % activities.length];
        client.user?.setPresence({ activities: [activity], status: 'online' });
        idx += 1;
      };
      applyPresence();
      setInterval(applyPresence, 60_000);
      logger.info(`Ready on ${client.guilds.cache.size} Guilds`);
      // force guild command registration so new commands wie /birthday sofort erscheinen
      if (context.commandHandler) {
        for (const [gid] of client.guilds.cache) {
          await context.commandHandler.registerGuildCommands(gid).catch((err) => logger.warn(`register commands failed for ${gid}: ${err}`));
        }
      }
      context.birthdays.startScheduler();
      context.birthdays.checkAndSend(true).catch(() => undefined);
      await context.reactionRoles.loadCache().catch(() => undefined);
      for (const gid of settingsStore.all().keys()) {
        context.reactionRoles.resyncGuild(gid).catch((err) => logger.warn(`reaction roles sync failed for ${gid}: ${err}`));
      }
      context.stats.startScheduler();
      for (const [gid] of client.guilds.cache) {
        context.stats.refreshGuild(gid).catch((err) => logger.warn(`stats refresh failed for ${gid}: ${err}`));
      }
    } catch (err) {
      logger.warn(`Ready handler failed: ${err}`);
    }
  }
};

export default event;
