import crypto from "crypto";

export class Encryption {
  constructor() {
    this.ALGORITHM = "aes-256-cbc";
    this.KEY = crypto
      .createHash("sha256")
      .update(process.env.ENCRYPTION_KEY)
      .digest();
  }

  encrypt(text) {
    const iv = crypto.randomBytes(16);
    const cipher = crypto.createCipheriv(this.ALGORITHM, this.KEY, iv);
    let encrypted = cipher.update(text, "utf8", "base64");
    encrypted += cipher.final("base64");
    return iv.toString("base64") + ":" + encrypted;
  }

  decrypt(encryptedText) {
    const [ivBase64, encrypted] = encryptedText.split(":");
    const iv = Buffer.from(ivBase64, "base64");
    const decipher = crypto.createDecipheriv(this.ALGORITHM, this.KEY, iv);
    let decrypted = decipher.update(encrypted, "base64", "utf8");
    decrypted += decipher.final("utf8");
    return decrypted;
  }
}
