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

const EmsPartsOrderGeneratePfhFile = async (
  partsOrder: EmsPartsOrder,
): Promise<boolean> => {
  try {
    const records = [
      {
        ID_PRO_NAM: "REPAIR FACILITY", // Job.id_pro_nam?.Value
        TAX_PRETHR: (partsOrder.job.tax_prethr || 0) * 100,
        TAX_THRAMT: (partsOrder.job.tax_thramt || 0) * 100,
        TAX_PSTTHR: (partsOrder.job.tax_pstthr || 0) * 100,
        TAX_TOW_IN: true, // Job.tax_tow_in?.Value
        TAX_TOW_RT: (partsOrder.job.tax_tow_rt || 0) * 100,
        TAX_STR_IN: true, // Job.tax_str_in?.Value
        TAX_STR_RT: (partsOrder.job.tax_str_rt || 0) * 100,
        TAX_SUB_IN: true, // Job.tax_sub_in?.Value
        TAX_SUB_RT: (partsOrder.job.tax_sub_rt || 0) * 100,
        TAX_BTR_IN: true, // Job.tax_btr_in?.Value
        TAX_LBR_RT:
          (partsOrder.job.bodyshop?.bill_tax_rates?.state_tax_rate || 0) * 100,
        TAX_GST_RT:
          (partsOrder.job.bodyshop?.bill_tax_rates?.federal_tax_rate || 0) *
          100,
        TAX_GST_IN: true, // Job.tax_gst_in?.Value
        ADJ_G_DISC: (partsOrder.job.adj_g_disc || 0) * 100,
        ADJ_TOWDIS: (partsOrder.job.adj_towdis || 0) * 100,
        ADJ_STRDIS: (partsOrder.job.adj_strdis || 0) * 100,
        ADJ_BTR_IN: null, // Job.adj_btr_in?.Value
        TAX_PREDIS: (partsOrder.job.tax_predis || 0) * 100,
      },
    ];

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

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

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

export default EmsPartsOrderGeneratePfhFile;
