import CryptoJS from 'crypto-js';

// AES encryption key and IV should be loaded from environment variables in production
const AES_KEY = import.meta.env.VITE_AES_KEY || 'default-aes-key-1234567890123456';
const AES_IV = import.meta.env.VITE_AES_IV || 'default-aes-iv-123456';

class SensitiveDataEncryptor {
  /**
   * Encrypt phone number using AES encryption
   * @param phone Phone number to encrypt
   * @returns Encrypted phone number
   */
  encryptPhone(phone: string): string {
    try {
      const key = CryptoJS.enc.Utf8.parse(AES_KEY);
      const iv = CryptoJS.enc.Utf8.parse(AES_IV);
      const encrypted = CryptoJS.AES.encrypt(phone, key, {
        iv: iv,
        mode: CryptoJS.mode.CBC,
        padding: CryptoJS.pad.Pkcs7
      });
      return encrypted.toString();
    } catch (error) {
      console.error('Failed to encrypt phone:', error);
      throw new Error('Phone encryption failed');
    }
  }

  /**
   * Decrypt phone number using AES encryption
   * @param encryptedPhone Encrypted phone number
   * @returns Decrypted phone number
   */
  decryptPhone(encryptedPhone: string): string {
    try {
      const key = CryptoJS.enc.Utf8.parse(AES_KEY);
      const iv = CryptoJS.enc.Utf8.parse(AES_IV);
      const decrypted = CryptoJS.AES.decrypt(encryptedPhone, key, {
        iv: iv,
        mode: CryptoJS.mode.CBC,
        padding: CryptoJS.pad.Pkcs7
      });
      return decrypted.toString(CryptoJS.enc.Utf8);
    } catch (error) {
      console.error('Failed to decrypt phone:', error);
      throw new Error('Phone decryption failed');
    }
  }

  /**
   * Encrypt general sensitive data
   * @param data Data to encrypt
   * @returns Encrypted data
   */
  encryptData(data: string): string {
    return this.encryptPhone(data);
  }

  /**
   * Decrypt general sensitive data
   * @param encryptedData Encrypted data
   * @returns Decrypted data
   */
  decryptData(encryptedData: string): string {
    return this.decryptPhone(encryptedData);
  }
}

export default new SensitiveDataEncryptor();