import type { BotContext } from '../../types.js';
import { logger } from '../../logger.js';
import { resolveHubJoin, resolveVoiceLeave } from './service.js';

export function registerTempVoiceEvents(context: BotContext): void {
  context.client.on('voiceStateUpdate', async (oldState, newState) => {
    try {
      const guild = newState.guild;
      const member = newState.member;
      if (!member || member.user.bot) {
        return;
      }

      const oldChannelId = oldState.channelId;
      const newChannelId = newState.channelId;

      if (newChannelId && newChannelId !== oldChannelId) {
        await resolveHubJoin(context, member, newChannelId);
      }

      if (oldChannelId && oldChannelId !== newChannelId) {
        await resolveVoiceLeave(context, guild, oldChannelId);
      }
    } catch (error) {
      logger.error({ error, userId: newState.id }, 'Temp voice state handler failed');
    }
  });
}
