import { DBFFile } from "dbffile";
import errorTypeCheck from "../../util/errorTypeCheck";
import { pfoFieldLineDescriptors } from "../util/ems-interface/fielddescriptors/pfo-field-descriptors";
import {
  deleteEmsFileIfExists,
  generateEmsOutFilePath,
} from "../util/ems-util";
import { EmsPartsOrder } from "./ems-parts-order-interfaces";

const EmsPartsOrderGeneratePfoFile = async (
  partsOrder: EmsPartsOrder,
): Promise<boolean> => {
  try {
    const records = []; //This was kept blank previously as well.

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

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

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

export default EmsPartsOrderGeneratePfoFile;
