import crypto from 'crypto';

/**
 * QR Code Encryption Utility
 * Encrypts QR code data (type and ID) for secure QR code generation
 * Uses AES-256-GCM encryption with the QRCODE_ENCRYPTION environment variable
 */
export class QRCodeEncryption {
  private static readonly ALGORITHM = 'aes-256-gcm';
  private static readonly IV_LENGTH = 16;
  private static readonly AUTH_TAG_LENGTH = 16;
  private static readonly SALT_LENGTH = 32;

  /**
   * Get encryption key from environment variable
   */
  private static getEncryptionKey(): Buffer {
    const key = process.env.QRCODE_ENCRYPTION;
    if (!key) {
      throw new Error('QRCODE_ENCRYPTION environment variable is not set');
    }
    // Convert base64 key to buffer
    return Buffer.from(key, 'base64');
  }

  public static encrypt(qrcodeId: string, type: string): string {
    try {
      const key = this.getEncryptionKey();

      // Create payload with type and ID
      const payload = JSON.stringify({
        id: qrcodeId,
        type: type,
        timestamp: Date.now(), // Add timestamp for additional security
      });

      // Generate random IV and salt
      const iv = crypto.randomBytes(this.IV_LENGTH);
      const salt = crypto.randomBytes(this.SALT_LENGTH);

      // Create cipher
      const cipher = crypto.createCipheriv(this.ALGORITHM, key, iv);

      // Encrypt the data
      let encrypted = cipher.update(payload, 'utf8', 'base64');
      encrypted += cipher.final('base64');

      // Get auth tag
      const authTag = cipher.getAuthTag();

      // Combine all parts: iv:authTag:salt:encryptedData
      return `${iv.toString('base64')}:${authTag.toString('base64')}:${salt.toString('base64')}:${encrypted}`;
    } catch (error) {
      console.error('Error encrypting QR code data:', error);
      throw new Error('Failed to encrypt QR code data');
    }
  }

  public static decrypt(encryptedData: string): {
    id: string;
    type: string;
    timestamp: number;
  } {
    try {
      const key = this.getEncryptionKey();

      // Split the encrypted data
      const parts = encryptedData.split(':');
      if (parts.length !== 4) {
        throw new Error('Invalid encrypted data format');
      }

      const [ivBase64, authTagBase64, saltBase64, encrypted] = parts;

      // Convert from base64
      const iv = Buffer.from(ivBase64, 'base64');
      const authTag = Buffer.from(authTagBase64, 'base64');
      const salt = Buffer.from(saltBase64, 'base64');

      // Create decipher
      const decipher = crypto.createDecipheriv(this.ALGORITHM, key, iv);
      decipher.setAuthTag(authTag);

      // Decrypt the data
      let decrypted = decipher.update(encrypted, 'base64', 'utf8');
      decrypted += decipher.final('utf8');

      // Parse the JSON payload
      const payload = JSON.parse(decrypted);

      return {
        id: payload.id,
        type: payload.type,
        timestamp: payload.timestamp,
      };
    } catch (error) {
      console.error('Error decrypting QR code data:', error);
      throw new Error('Failed to decrypt QR code data');
    }
  }

  public static isTimestampValid(
    timestamp: number,
    maxAgeMs: number = 10 * 365 * 24 * 60 * 60 * 1000
  ): boolean {
    const now = Date.now();
    const age = now - timestamp;
    return age >= 0 && age <= maxAgeMs;
  }
}
