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

const EmsPartsOrderGenerateTtlFile = async (
  partsOrder: EmsPartsOrder,
): Promise<boolean> => {
  try {
    //TODO: Add CIECA STL to parts order.
    const records = uppercaseObjectKeys(partsOrder.job.cieca_ttl?.data);

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

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

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

export default EmsPartsOrderGenerateTtlFile;
