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

const EmsPartsOrderGenerateEnvFile = async (
  partsOrder: EmsPartsOrder,
): Promise<boolean> => {
  try {
    const records = [
      {
        EST_SYSTEM: "C",
        RO_ID: partsOrder.job.ro_number,
        ESTFILE_ID: partsOrder.job.ciecaid,
        STATUS: false,
        INCL_ADMIN: true,
        INCL_VEH: true,
        INCL_EST: true,
        INCL_PROFL: true,
        INCL_TOTAL: true,
        INCL_VENDR: false,
      },
    ];

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

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

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

export default EmsPartsOrderGenerateEnvFile;
