import crypto from 'crypto';

export class PinEncryption {
  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.QRCODE_PIN_HASHING;
    if (!key) {
      throw new Error('QRCODE_PIN_HASHING environment variable is not set');
    }

    // Convert base64 key to buffer and ensure it's 32 bytes for AES-256
    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 a PIN using AES-256-CBC
   * @param pin - The PIN to encrypt
   * @returns Encrypted PIN as base64 string (includes IV)
   */
  public static encryptPin(pin: string): string {
    try {
      const key = this.getEncryptionKey();
      const iv = crypto.randomBytes(this.IV_LENGTH);

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

      let encrypted = cipher.update(pin, '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 PIN:', error);
      throw new Error('Failed to encrypt PIN');
    }
  }

  /**
   * Decrypt a PIN using AES-256-CBC
   * @param encryptedPin - The encrypted PIN as base64 string
   * @returns Decrypted PIN as string
   */
  public static decryptPin(encryptedPin: string): string {
    console.log(encryptedPin);
    try {
      const key = this.getEncryptionKey();
      const combined = Buffer.from(encryptedPin, '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');

      return decrypted;
    } catch (error) {
      console.error('Error decrypting PIN:', error);
      throw new Error('Failed to decrypt PIN');
    }
  }

  /**
   * Verify if a plain PIN matches an encrypted PIN
   * @param plainPin - The plain text PIN to verify
   * @param encryptedPin - The encrypted PIN to compare against
   * @returns True if PINs match, false otherwise
   */
  public static verifyPin(plainPin: string, encryptedPin: string): boolean {
    try {
      const decryptedPin = this.decryptPin(encryptedPin);
      console.log(`================ VERIFY PIN ==============`);
      console.log(plainPin);
      console.log(encryptedPin);
      console.log(decryptedPin);
      console.log(`================ VERIFY PIN ==============`);

      return plainPin === decryptedPin;
    } catch (error) {
      console.error('Error verifying PIN:', error);
      return false;
    }
  }

  /**
   * Hash a PIN using bcrypt (alternative approach for one-way hashing)
   * @param pin - The PIN to hash
   * @returns Hashed PIN
   */
  public static async hashPin(pin: string): Promise<string> {
    const bcrypt = require('bcrypt');
    const saltRounds = 12;
    return await bcrypt.hash(pin, saltRounds);
  }

  /**
   * Verify a PIN against a bcrypt hash
   * @param pin - The plain text PIN
   * @param hashedPin - The bcrypt hashed PIN
   * @returns True if PIN matches hash, false otherwise
   */
  public static async verifyPinHash(pin: string, hashedPin: string): Promise<boolean> {
    const bcrypt = require('bcrypt');
    return await bcrypt.compare(pin, hashedPin);
  }
}
