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 { env } from '../config/env';
import { PrismaShardStatusRepository } from '@kord/db';
import { prisma } from '../database';
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);

    const shardId = client.shard?.ids[0] ?? 0;
    const guildIds = Array.from(client.guilds.cache.keys());
    const shardRepo = new PrismaShardStatusRepository(prisma);
    await shardRepo.upsertStatus(shardId, 'READY', guildIds)
      .catch((e: Error) => logger.error('Failed to update shard status:', e));

    try {
      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.`);
    } 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(() => {});
    });
  },
};
