// const { createHmac } = require("node:crypto");

// const encrypt = (data, key) => {
//   const hash = createHmac("sha256", key).update(data).digest("base64");
//   return hash;
// };
const {
  createCipheriv,
  createDecipheriv,
  randomBytes,
  createHash,
} = require("crypto");

const generateKey = (key) => {
  return createHash("sha256").update(key).digest(); // Produces a 32-byte key
};

// Function to encrypt data
const encrypt = (data, key) => {
  const derivedKey = generateKey(key); // Derive a 32-byte key
  const iv = randomBytes(16); // Generate a random initialization vector
  const cipher = createCipheriv("aes-256-cbc", derivedKey, iv);
  const encrypted = Buffer.concat([
    cipher.update(data, "utf8"),
    cipher.final(),
  ]);
  const combined = `${iv.toString("base64")}|${encrypted.toString("base64")}`; // Combine IV and data
  return Buffer.from(combined).toString("base64"); // Encode combined string in Base64
  //return { iv: iv.toString("hex"), encryptedData: encrypted.toString("hex") };
};

// Function to decrypt data
const decrypt = (combinedData, key) => {
  const derivedKey = generateKey(key);
  const decoded = Buffer.from(combinedData, "base64").toString("utf8"); // Decode combined data
  const [iv, encryptedData] = decoded.split("|"); // Split into IV and encrypted data
  const decipher = createDecipheriv(
    "aes-256-cbc",
    derivedKey,
    Buffer.from(iv, "base64")
  );
  const decrypted = Buffer.concat([
    decipher.update(Buffer.from(encryptedData, "base64")), // Decode data from Base64
    decipher.final(),
  ]);
  return decrypted.toString("utf8");
};

module.exports = { encrypt, decrypt, generateKey };
