const fs = require("fs");
const path = require("path");
const { default: InstanceMgr } = require("../../utils/instanceMgr");

const fixtureDir = path.join(__dirname, "..", "test", "fixtures", "job-totals");

/**
 * Custom serializer for Dinero.js objects.
 * @param key
 * @param value
 * @returns {*}
 */
const serializeDinero = (key, value) => {
  if (value && typeof value === "object" && typeof value.toObject === "function") {
    return value.toObject();
  }
  return value;
};

/**
 * Capture a fixture for job totals.
 * @param inputData
 * @param outputData
 * @param saveLocally
 */
const captureFixture = (inputData, outputData, saveLocally) => {
  const fileName = `${inputData.id}.json`;
  const filePath = path.join(fixtureDir, fileName);

  const dataToSave = {
    environment: InstanceMgr({
      imex: "ca",
      rome: "us"
    }),
    meta: {
      ro_number: inputData.ro_number,
      updated_at: inputData.updated_at
    },
    input: inputData,
    output: outputData
  };

  // Save the file using our custom serializer.
  if (saveLocally) {
    if (!fs.existsSync(fixtureDir)) {
      fs.mkdirSync(fixtureDir, { recursive: true });
    }

    fs.writeFileSync(filePath, JSON.stringify(dataToSave, serializeDinero, 2), "utf8");
  }

  return dataToSave;
};

module.exports = {
  captureFixture,
  serializeDinero
};
