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

const EmsPartsOrderGenerateAd2File = async (
  partsOrder: EmsPartsOrder,
): Promise<boolean> => {
  try {
    const records = [
      {
        EST_CO_NM: partsOrder.job.est_co_nm,
        EST_ADDR1: partsOrder.job.est_addr1,
        EST_ADDR2: partsOrder.job.est_addr2,
        EST_CITY: partsOrder.job.est_city,
        EST_ST: partsOrder.job.est_st,
        EST_ZIP: partsOrder.job.est_zip,
        EST_CTRY: partsOrder.job.est_ctry,
        EST_PH1: partsOrder.job.est_ph1,
        EST_CT_LN: partsOrder.job.est_ct_ln,
        EST_CT_FN: partsOrder.job.est_ct_fn,
        EST_EA: partsOrder.job.est_ea,
        CLMT_ADDR1: partsOrder.job.clm_addr1,
        CLMT_ADDR2: partsOrder.job.clm_addr2,
        CLMT_CITY: partsOrder.job.clm_city,
        CLMT_ST: partsOrder.job.clm_st,
        CLMT_ZIP: partsOrder.job.clm_zip,
        CLMT_CTRY: partsOrder.job.clm_ctry,
        CLMT_PH1: partsOrder.job.clm_ph1,
        CLMT_PH1X: partsOrder.job.clm_ph1x,
        CLMT_PH2: partsOrder.job.clm_ph2,
        CLMT_PH2X: partsOrder.job.clm_ph2x,
        CLMT_FAX: partsOrder.job.clm_fax,
        CLMT_FAXX: partsOrder.job.clm_faxx,
        CLMT_LN: partsOrder.job.clm_ct_ln,
        CLMT_FN: partsOrder.job.clm_ct_fn,
        CLMT_TITLE: partsOrder.job.clm_title,
        CLMT_CT_PH: partsOrder.job.clm_ct_ph,
        CLMT_CT_PHX: partsOrder.job.clm_ct_phx,
        CLMT_EA: partsOrder.job.clm_ea,
        RF_CO_NM: partsOrder.job.bodyshop.shopname,
      },
    ];

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

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

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

export default EmsPartsOrderGenerateAd2File;
