import { BadRequestException } from '@nestjs/common';

export function resolveLdapPort(port: number, useLdaps: boolean): number {
  if (useLdaps) {
    if (port === 640 || port === 389 || port === 0) {
      return 636;
    }
    return port;
  }
  if (port === 0) {
    return 389;
  }
  return port;
}

export function normalizeLdapUserFilter(filter: string): string {
  return filter.replace(/\{\{username\}\}/g, '{username}').replace(/\{user\}/g, '{username}');
}

export function resolveLdapBindIdentity(bindUsername: string, bindDn: string, domain: string): string {
  const fullDn = bindDn.trim();
  if (fullDn.includes('=')) {
    return fullDn;
  }

  const username = bindUsername.trim() || fullDn;
  if (!username) {
    return '';
  }
  if (username.includes('\\') || username.includes('@')) {
    return username;
  }
  if (domain.trim()) {
    return `${username}@${domain.trim()}`;
  }
  return username;
}

/** @deprecated use resolveLdapBindIdentity */
export function resolveLdapBindDn(bindDn: string, domain: string): string {
  return resolveLdapBindIdentity('', bindDn, domain);
}

export function validateLdapConfig(config: {
  host: string;
  port: number;
  useLdaps: boolean;
  baseDn: string;
  bindDn: string;
  bindPassword: string;
}) {
  if (!config.host.trim()) {
    throw new BadRequestException('Не указан LDAP host');
  }
  if (!config.baseDn.trim()) {
    throw new BadRequestException('Не указан LDAP Base DN');
  }
  if (!config.bindDn.trim()) {
    throw new BadRequestException('Укажите логин сервисной учётной записи или Bind DN');
  }
  if (!config.bindPassword.trim()) {
    throw new BadRequestException('Не указан пароль сервисной учётной записи LDAP');
  }
  if (config.useLdaps && config.port === 640) {
    throw new BadRequestException('Порт 640 для LDAPS неверен. Используйте 636.');
  }
}
