import type { BotContext } from '../../types.js';
import { getVerificationConfig } from './service.js';
import { PermissionFlagsBits } from 'discord.js';
import { logger } from '../../logger.js';

export function registerVerificationEvents(context: BotContext): void {
  context.client.on('guildMemberAdd', async (member) => {
    const config = await getVerificationConfig(context.prisma, member.guild.id);
    if (!config.enabled || !config.unverifiedRoleId) {
      return;
    }
    if (config.verifiedRoleId && member.roles.cache.has(config.verifiedRoleId)) {
      return;
    }
    const me = member.guild.members.me;
    if (!me?.permissions.has(PermissionFlagsBits.ManageRoles)) {
      return;
    }
    const role = member.guild.roles.cache.get(config.unverifiedRoleId);
    if (!role || role.position >= me.roles.highest.position) {
      return;
    }
    await member.roles.add(role).catch((error) => {
      logger.warn({ error, memberId: member.id }, 'Failed to assign unverified role');
    });
  });
}
