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

const EmsPartsOrderGenerateVehFile = async (
  partsOrder: EmsPartsOrder,
): Promise<boolean> => {
  try {
    const records = [
      {
        IMPACT_1: partsOrder.job.area_of_damage?.impact1 || null,
        IMPACT_2: partsOrder.job.area_of_damage?.impact2 || null,
        DMG_MEMO: null,
        DB_V_CODE: "",
        PLATE_NO: partsOrder.job.plate_no || null,
        PLATE_ST: partsOrder.job.plate_st || null,
        V_VIN: partsOrder.job.v_vin || null,
        V_COND: "",
        V_PROD_DT: "",
        V_MODEL_YR: partsOrder.job.v_model_yr || null,
        V_MAKECODE: "",
        V_MAKEDESC: partsOrder.job.v_make_desc || null,
        V_MODEL: partsOrder.job.v_model_desc || null,
        V_TYPE: partsOrder.job.vehicle?.v_type || null,
        V_BSTYLE: partsOrder.job.vehicle?.v_bstyle || null,
        V_TRIMCODE: partsOrder.job.vehicle?.v_trimcode || null,
        TRIM_COLOR: partsOrder.job.vehicle?.trim_color || null,
        V_MLDGCODE: partsOrder.job.vehicle?.v_mldgcode || null,
        V_ENGINE: partsOrder.job.vehicle?.v_engine || null,
        V_MILEAGE: partsOrder.job.vehicle?.v_mileage || null,
        V_OPTIONS: null,
        V_COLOR: partsOrder.job.vehicle?.v_color || null,
        V_TONE: Number(partsOrder.job.vehicle?.v_tone) || null,
        V_STAGE: null,
        PAINT_CD1: partsOrder.job.vehicle?.v_paint_codes?.paint_cd1 || "",
        PAINT_CD2: partsOrder.job.vehicle?.v_paint_codes?.paint_cd2 || "",
        PAINT_CD3: partsOrder.job.vehicle?.v_paint_codes?.paint_cd3 || "",
        V_MEMO: null,
      },
    ];

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

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

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

export default EmsPartsOrderGenerateVehFile;
