import { DBFFile } from "dbffile";
import { linFieldDescriptors } from "../util/ems-interface/fielddescriptors/lin-field-descriptor";
import { deleteEmsFileIfExists, generatePpcFilePath } from "../util/ems-util";
import { PpcJob } from "./ppc-handler";
import errorTypeCheck from "../../util/errorTypeCheck";

const GenerateLinFile = async (job: PpcJob): Promise<boolean> => {
  try {
    const records = job.joblines.map((line) => {
      return {
        //TODO: There are missing types here. May require server side updates, but we are missing things like LINE_NO, LINE_IND, etc.
        TRAN_CODE: "2",
        UNQ_SEQ: line.unq_seq,
        ACT_PRICE: line.act_price,
      };
    });

    await deleteEmsFileIfExists(generatePpcFilePath(`${job.ciecaid}.LIN`));

    const dbf = await DBFFile.create(
      generatePpcFilePath(`${job.ciecaid}.LIN`),
      linFieldDescriptors,
    );

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

export default GenerateLinFile;
