import Password from "../tools/Password";
import crypto from "crypto";
import { secureValuesPrivateKey } from "../../constants";
import GenericError from "../../Errors/GenericError";

const privateKey = crypto.createPrivateKey(secureValuesPrivateKey);

export const readSecureValue = (
  encryptedContent: string,
  hash?: string,
): string => {
  let decrypted: Buffer;

  try {
    // Decrypt the content using the .secureValues.key private key
    decrypted = crypto.privateDecrypt(
      {
        key: privateKey,
        padding: crypto.constants.RSA_PKCS1_OAEP_PADDING,
        oaepHash: "sha256",
      },
      Buffer.from(encryptedContent, "base64"),
    );
  } catch {
    throw new GenericError({
      name: "SecureValueDecryptionError",
      message:
        "Unable to decrypt secure value. The value was encrypted with a different key and must be re-entered.",
      cause:
        "RSA key mismatch — the current private key does not match the public key used to encrypt this value.",
      status: 422,
    });
  }

  const content = decrypted.toString("utf-8");

  // Optionally validate the hash if provided
  if (hash) {
    const isValid = Password.validate(content, hash);
    if (!isValid) {
      throw new Error("Secure value hash validation failed");
    }
  }

  return content;
};
