import crypto from "node:crypto";

import { paymentConfig } from "$config/index.js";

export const buildAdditionalData = ({
  identifier,
  personality = "0",
  salt,
  data = "",
}) => {
  const key = Buffer.from(paymentConfig.manaConfig.keyBase64 || "", "base64");
  const iv = Buffer.from(paymentConfig.manaConfig.ivBase64 || "", "base64");

  if (key.length !== 16 || iv.length !== 16) {
    const error = new Error(
      "Invalid MANA key/iv. AES-128-CBC requires 16 bytes each.",
    );
    error.status = 500;
    throw error;
  }

  if (!identifier) {
    const error = new Error(
      "National identifier is required for MANA AdditionalData.",
    );
    error.status = 422;
    throw error;
  }

  const plain = `${personality}|${identifier}|${salt}`;
  const cipher = crypto.createCipheriv("aes-128-cbc", key, iv);
  const encrypted = Buffer.concat([
    cipher.update(plain, "utf8"),
    cipher.final(),
  ]).toString("base64");

  return JSON.stringify({
    NationalEncryptedId: encrypted,
    ThirdPartyCode: paymentConfig.manaConfig.thirdPartyCode,
    Data: data,
  });
};
