import crypto from "node:crypto";

export function encrypt(text: string) {
  const secret = Buffer.from(process.env.CIPHER_SECRET!, "hex");
  const iv = Buffer.from(process.env.CIPHER_IV!, "hex");
  const cipher = crypto.createCipheriv("aes-256-cbc", secret, iv);
  let encrypted = cipher.update(text, "utf8", "hex");
  encrypted += cipher.final("hex");
  return encrypted;
}

export function decrypt(encryptedText: string) {
  const secret = Buffer.from(process.env.CIPHER_SECRET!, "hex");
  const iv = Buffer.from(process.env.CIPHER_IV!, "hex");
  const decipher = crypto.createDecipheriv("aes-256-cbc", secret, iv);
  let decrypted = decipher.update(encryptedText, "hex", "utf8");
  decrypted += decipher.final("utf8");
  return decrypted;
}

export function isValidEncrypted(encryptedText: string): boolean {
  try {
    decrypt(encryptedText);
    return true;
  } catch (err) {
    return false;
  }
}
