import crypto from 'crypto';

export class MedicalEncryption {
  private static readonly ALGORITHM = 'aes-256-cbc';
  private static readonly IV_LENGTH = 16; // CBC IV length

  /**
   * Get the encryption key from environment variable
   */
  private static getEncryptionKey(): Buffer {
    const key = process.env.MEDICAL_ENCRYPTION_KEY || process.env.QRCODE_PIN_HASHING;
    if (!key) {
      throw new Error(
        'MEDICAL_ENCRYPTION_KEY or QRCODE_PIN_HASHING environment variable is required'
      );
    }

    const keyBuffer = Buffer.from(key, 'base64');
    if (keyBuffer.length !== 32) {
      // If key is not 32 bytes, hash it to get a proper 32-byte key
      return crypto.createHash('sha256').update(keyBuffer).digest();
    }
    return keyBuffer;
  }

  /**
   * Encrypt medical type details using AES-256-CBC
   * @param data - The medical data object to encrypt
   * @returns Encrypted data as base64 string (includes IV)
   */
  public static encryptMedicalData(data: any): string {
    try {
      const key = this.getEncryptionKey();
      const iv = crypto.randomBytes(this.IV_LENGTH);

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

      // Convert data to JSON string before encryption
      const jsonData = JSON.stringify(data);
      let encrypted = cipher.update(jsonData, 'utf8', 'hex');
      encrypted += cipher.final('hex');

      // Combine IV + encrypted data
      const combined = Buffer.concat([iv, Buffer.from(encrypted, 'hex')]);

      return combined.toString('base64');
    } catch (error) {
      console.error('Error encrypting medical data:', error);
      throw new Error('Failed to encrypt medical data');
    }
  }

  /**
   * Decrypt medical type details using AES-256-CBC
   * @param encryptedData - The encrypted data as base64 string
   * @returns Decrypted data as object
   */
  public static decryptMedicalData(encryptedData: string): any {
    try {
      const key = this.getEncryptionKey();
      const combined = Buffer.from(encryptedData, 'base64');

      // Extract IV and encrypted data
      const iv = combined.subarray(0, this.IV_LENGTH);
      const encrypted = combined.subarray(this.IV_LENGTH);

      const decipher = crypto.createDecipheriv(this.ALGORITHM, key, iv);

      let decrypted = decipher.update(encrypted.toString('hex'), 'hex', 'utf8');
      decrypted += decipher.final('utf8');

      // Parse JSON string back to object
      return JSON.parse(decrypted);
    } catch (error) {
      console.error('Error decrypting medical data:', error);
      throw new Error('Failed to decrypt medical data');
    }
  }

  /**
   * Check if data is encrypted (base64 format with proper length)
   * @param data - The data to check
   * @returns True if data appears to be encrypted
   */
  public static isEncrypted(data: any): boolean {
    if (typeof data !== 'string') {
      return false;
    }

    try {
      const buffer = Buffer.from(data, 'base64');
      // Check if it's a valid base64 string and has minimum length (IV + some data)
      return buffer.length > this.IV_LENGTH;
    } catch {
      return false;
    }
  }
}
