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 dateNow = new Date();
    const formatTime = (date: Date): string =>
      `${date.getHours().toString().padStart(2, "0")}${date.getMinutes().toString().padStart(2, "0")}${date.getSeconds().toString().padStart(2, "0")}`;

    const {
      job: { ro_number, ciecaid },
    } = partsOrder;

    // Find the highest line_ind value
    const lineInds = partsOrder.parts_order_lines.map(
      (line) => line.jobline.line_ind,
    );
    const getNumber = (str: string): number => {
      const match = str.match(/(\d+)$/);
      return match ? parseInt(match[1], 10) : 0;
    };
    const highestLineInd = lineInds.reduce(
      (max, current) => (getNumber(current) > getNumber(max) ? current : max),
      lineInds[0] || "",
    );

    const records = [
      {
        EST_SYSTEM: "M",
        SW_VERSION: "25.3",
        DB_VERSION: "OCT_25_V",
        DB_DATE: dateNow,
        RO_ID: ro_number,
        ESTFILE_ID: ciecaid,
        SUPP_NO: highestLineInd ? getNumber(highestLineInd).toString() : "1",
        EST_CTRY: "CAN",
        TOP_SECRET: "00000000-0000-0000-0000-000000000000",
        TRANS_TYPE: highestLineInd ? highestLineInd.charAt(0) : "S",
        STATUS: false,
        CREATE_DT: dateNow,
        CREATE_TM: formatTime(dateNow),
        TRANSMT_DT: dateNow,
        TRANSMT_TM: formatTime(dateNow),
        INCL_ADMIN: true,
        INCL_VEH: true,
        INCL_EST: true,
        INCL_PROFL: false,
        INCL_TOTAL: false,
        INCL_VENDR: false,
        EMS_VER: "2.0",
      },
    ];

    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;
