import { UUID } from "crypto";
import log from "electron-log/main";
import express from "express";
import _ from "lodash";
import errorTypeCheck from "../../util/errorTypeCheck";
import store from "../store/store";
import createdDirectoryIfNotExist from "../util/createDirectoryIfNotExist";
import GenerateEnvFile from "./ppc-generate-env";
import GenerateLinFile from "./ppc-generate-lin";

const handlePartsPriceChangeRequest = async (
  req: express.Request,
  res: express.Response,
): Promise<void> => {
  //Route handler here only.

  const { job } = req.body as { job: PpcJob };
  try {
    await generatePartsPriceChange(job);
    res.status(200).json({ success: true });
  } catch (error) {
    log.error("Error generating parts price change", errorTypeCheck(error));
    res.status(500).json({
      success: false,
      error: "Error generating parts price change.",
      ...errorTypeCheck(error),
    });
  }
  return;
};

const generatePartsPriceChange = async (job: PpcJob): Promise<void> => {
  log.debug(" Generating parts price change");
  //Check to make sure that the PPC Output file path exists. If it doesn't, create it. If it's not set, abandon ship.

  const ppcOutFilePath: string | null = store.get("settings.ppcFilePath");
  if (_.isEmpty(ppcOutFilePath) || ppcOutFilePath === null) {
    log.error("PPC file path is not set");
    throw new Error("PPC file path is not set");
  }
  try {
    createdDirectoryIfNotExist(ppcOutFilePath);

    await GenerateLinFile(job);
    await GenerateEnvFile(job);
  } catch (error) {
    log.error("Error generating parts price change", errorTypeCheck(error));
    throw error;
  }
};
export interface PpcJob {
  id: UUID;
  ciecaid: string;
  ro_number: string;
  joblines: {
    removed: boolean;
    act_price_before_ppc: number | null;
    id: string;
    act_price: number;
    unq_seq: string; //TODO: Might be a number.
  }[];
  bodyshop: {
    timezone: string;
  };
}

export { handlePartsPriceChangeRequest };
