import Cryptr from "cryptr";
import { handleErrorWithInfo } from "./errors";

const CRYPTR = new Cryptr(String(process.env.JOB_QUEUE_ENCRYPTION_KEY));

/**
 * Encrypt the data payload and return an object with the encrypted data.
 * @param {Record<string, unknown>} payload An object of data to encrypt
 * @returns {{ encrypted: string } | void} Returns an object with an encrypted key containing the encrypted data as a string
 */
export function encryptPayload(
  payload: Record<string, unknown>,
): { encrypted: string } | void {
  try {
    const stringify = JSON.stringify(payload);
    const encrypted = CRYPTR.encrypt(stringify);
    return { encrypted };
  } catch (err) {
    handleErrorWithInfo({
      message: `Failed to encrypt a job payload`,
      error: err as Error,
      job: "Encrypt Payload",
      handle: false,
    });
  }
}

/**
 * Decrypt a data string and parse into an object. This should only be used with data encrypted using the encryptPayload function
 * @param {{ encrypted: string }} encryptedData an object with a key called encrypted with an encryted stringified payload to decrypt
 * @returns {Record<string, unknown> | void}
 */
export function decryptPayload(encryptedData: {
  encrypted: string;
}): Record<string, unknown> | void {
  try {
    const decrypted = CRYPTR.decrypt(encryptedData.encrypted);
    const payload = JSON.parse(decrypted);
    return payload;
  } catch (err) {
    handleErrorWithInfo({
      message: `Failed to decrypt a job payload`,
      error: err as Error,
      job: "Decrypt Payload",
      handle: false,
    });
  }
}
