import { Events } from 'discord.js';
import { KordClient } from '../client/KordClient';
import { logger } from '../utils/logger';
import { VoiceService } from '../services/VoiceService';
import { PresenceService } from '../services/PresenceService';
import { EventService } from '../services/EventService';
import { auditLogService } from '../services/AuditLogService';
import { tryAcquireLock } from '../cache';
import { env } from '../config/env';

export default {
  name: Events.ClientReady,
  once: true,
  async execute(client: KordClient) {
    logger.info(`Ready! Logged in as ${client.user?.tag}`);
    await VoiceService.syncChannels(client);
    PresenceService.startActivePresence(client);
    EventService.startReminderLoop(client);

    try {
      const lockKey = 'commands:sync:lock';
      // EX 300 = 5 minutes lock. Only one instance needs to do this per boot cycle.
      const acquired = await tryAcquireLock(lockKey, 300);
      
      if (acquired) {
        const commandsData = Array.from(client.commands.values()).map(c => c.data.toJSON());
        await client.application?.commands.set(commandsData);
        logger.info(`Successfully registered ${commandsData.length} global application commands.`);
      } else {
        logger.info('Global commands registration skipped (already handled by another instance).');
      }
    } catch (e) {
      logger.error('Failed to register global commands', e);
    }

    client.guilds.cache.forEach(guild => {
      auditLogService.log(guild, {
        category: 'BOOT',
        severity: 'INFO',
        title: 'Bot Online',
        description: `Kord instance **[${env.INSTANCE_ID}]** has successfully started or reconnected.`
      }).catch(() => {});
    });
  },
};
