import * as crypto from 'crypto';

const ALGORITHM = 'aes-256-gcm';
const IV_LENGTH = 16;
const TAG_LENGTH = 16;

export class CryptoUtil {
  static encrypt(plaintext: string, masterKey: string): { encrypted: Buffer; iv: Buffer } {
    const key = crypto.scryptSync(masterKey, 'it0-salt', 32);
    const iv = crypto.randomBytes(IV_LENGTH);
    const cipher = crypto.createCipheriv(ALGORITHM, key, iv);
    const encrypted = Buffer.concat([cipher.update(plaintext, 'utf8'), cipher.final()]);
    const tag = cipher.getAuthTag();
    return {
      encrypted: Buffer.concat([encrypted, tag]),
      iv,
    };
  }

  static decrypt(encrypted: Buffer, iv: Buffer, masterKey: string): string {
    const key = crypto.scryptSync(masterKey, 'it0-salt', 32);
    const tag = encrypted.subarray(encrypted.length - TAG_LENGTH);
    const data = encrypted.subarray(0, encrypted.length - TAG_LENGTH);
    const decipher = crypto.createDecipheriv(ALGORITHM, key, iv);
    decipher.setAuthTag(tag);
    return decipher.update(data) + decipher.final('utf8');
  }
}
