import crypto from "crypto";
function encrypt(plainText: any, cryptKey: any) {
  const cipher = "aes-256-cbc";

  // Prepare key
  const keyBuffer = Buffer.from(cryptKey, "utf8");
  let key = keyBuffer;
  if (key.length < 32) {
    key = Buffer.concat([key, Buffer.alloc(32 - key.length)], 32);
  } else if (key.length > 32) {
    key = key.slice(0, 32);
  }

  // Generate a random IV
  const ivlen = 16;
  const iv = crypto.randomBytes(ivlen);

  // Create cipher
  const cipherInstance = crypto.createCipheriv(cipher, key, iv);
  let encrypted = cipherInstance.update(plainText, "utf8", "binary");
  encrypted += cipherInstance.final("binary");
  const ciphertext = Buffer.from(encrypted, "binary");

  // Generate HMAC for integrity verification
  const hmac = crypto.createHmac("sha256", key);
  hmac.update(ciphertext);
  const hmacDigest = hmac.digest();

  // Combine IV, HMAC, and ciphertext
  const resultBuffer = Buffer.concat([iv, hmacDigest, ciphertext]);
  return resultBuffer.toString("base64");
}

export default function encryptData(data: any) {
  try {
    console.log(data);
    const key = process.env.NEXT_PUBLIC_ENC_KEY;
    console.log("Key used:", key);

    if (!key)
      throw new Error("Encryption key not found in environment variables.");

    const enc = encrypt(data, key); // encrypt data
    console.log(enc);
    return enc;
  } catch (error) {
    return;
  }
}
