import { Injectable, Logger } from '@nestjs/common';
import { authenticator } from 'otplib';
import * as QRCode from 'qrcode';

/**
 * TotpService - TOTP 2FA (Time-based One-Time Password).
 *
 * Verwendet den Google Authenticator kompatiblen TOTP-Algorithmus.
 * Secrets werden verschluesselt in der Datenbank gespeichert.
 */
@Injectable()
export class TotpService {
  private readonly logger = new Logger(TotpService.name);

  constructor() {
    // TOTP Konfiguration
    authenticator.options = {
      step: 30, // 30 Sekunden
      window: 1, // +/- 1 Schritt Toleranz
      digits: 6,
    };
  }

  /**
   * Neues TOTP-Secret generieren.
   */
  generateSecret(): string {
    return authenticator.generateSecret();
  }

  /**
   * QR-Code als Data-URL generieren (fuer Authenticator-App Setup).
   */
  async generateQrCode(email: string, secret: string): Promise<string> {
    const otpauthUrl = authenticator.keyuri(
      email,
      'INSIGHT Platform',
      secret,
    );
    return QRCode.toDataURL(otpauthUrl);
  }

  /**
   * TOTP-Code verifizieren.
   */
  verify(token: string, secret: string): boolean {
    try {
      return authenticator.verify({ token, secret });
    } catch {
      this.logger.warn('TOTP-Verifizierung fehlgeschlagen');
      return false;
    }
  }
}
