import { Injectable, Logger } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';

export interface LdapConnectionConfig {
  host: string;
  port: number;
  useLdaps: boolean;
  skipTlsVerify: boolean;
  domain: string;
  baseDn: string;
  bindDn: string;
  bindPassword: string;
  userFilter: string;
  usernameAttr: string;
  emailAttr: string;
  displayNameAttr: string;
}

export interface LdapAuthResult {
  dn: string;
  username: string;
  email?: string;
  displayName: string;
}

@Injectable()
export class LdapClientService {
  private readonly logger = new Logger(LdapClientService.name);

  constructor(private readonly config: ConfigService) {}

  private get baseUrl() {
    return this.config.get<string>('LDAP_AUTH_URL', 'http://ldap-auth:8086').replace(/\/$/, '');
  }

  async authenticate(config: LdapConnectionConfig, username: string, password: string): Promise<LdapAuthResult> {
    try {
      const response = await fetch(`${this.baseUrl}/authenticate`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ config, username, password })
      });

      const payload = (await response.json()) as {
        success?: boolean;
        dn?: string;
        username?: string;
        email?: string;
        displayName?: string;
        error?: string;
      };

      if (!response.ok || !payload.success || !payload.dn) {
        throw new Error(payload.error || 'Не удалось выполнить LDAP-аутентификацию');
      }

      return {
        dn: payload.dn,
        username: payload.username ?? username,
        email: payload.email,
        displayName: payload.displayName ?? payload.username ?? username
      };
    } catch (error) {
      this.logger.warn(`LDAP auth failed: ${error instanceof Error ? error.message : error}`);
      throw error;
    }
  }
}
