import { DBFFile } from "dbffile";
import errorTypeCheck from "../../util/errorTypeCheck";
import { DecodedPfpLine } from "../decoder/decode-pfp.interface";
import { pfpFieldLineDescriptors } from "../util/ems-interface/fielddescriptors/pfp-field-descriptors";
import {
  deleteEmsFileIfExists,
  generateEmsOutFilePath,
} from "../util/ems-util";
import uppercaseObjectKeys from "../util/uppercaseObjectKeys";
import { EmsPartsOrder } from "./ems-parts-order-interfaces";

const EmsPartsOrderGeneratePfpFile = async (
  partsOrder: EmsPartsOrder,
): Promise<boolean> => {
  try {
    const records = Object.keys(partsOrder.job.parts_tax_rates).map((key) => {
      const record: DecodedPfpLine = partsOrder.job.parts_tax_rates[key];
      return uppercaseObjectKeys(record);
    });

    await deleteEmsFileIfExists(
      generateEmsOutFilePath(`${partsOrder.job.ciecaid}.PFP`),
    );

    const dbf: DBFFile = await DBFFile.create(
      generateEmsOutFilePath(`${partsOrder.job.ciecaid}.PFP`),
      pfpFieldLineDescriptors,
    );

    await dbf.appendRecords(records);
    console.log(`${records.length} PFP file records added.`);
    return true;
  } catch (error) {
    console.error("Error generating PFP file:", errorTypeCheck(error));
    return false;
  }
};

export default EmsPartsOrderGeneratePfpFile;
