import path from "path";
import store from "../store/store";
import fs from "fs";

const generatePpcFilePath = (filename: string): string => {
  const ppcOutFilePath: string | null = store.get("settings.ppcFilePath");
  if (!ppcOutFilePath) {
    throw new Error("PPC file path is not set");
  }
  return path.resolve(ppcOutFilePath, filename);
};

const generateEmsOutFilePath = (filename: string): string => {
  const emsOutFilePath: string | null = store.get("settings.emsOutFilePath");
  if (!emsOutFilePath) {
    throw new Error("EMS Out file path is not set");
  }
  return path.resolve(emsOutFilePath, filename);
};

const deleteEmsFileIfExists = async (filename: string): Promise<void> => {
  // Check if the file exists and delete it if it does
  try {
    await fs.promises.access(filename); // Check if the file exists
    await fs.promises.unlink(filename); // Delete the file
    console.log(`Existing file at ${filename} deleted.`);
  } catch (err) {
    if ((err as NodeJS.ErrnoException).code !== "ENOENT") {
      // If the error is not "file not found", rethrow it
      throw err;
    }
    console.log(`No existing file found at ${filename}.`);
  }
};

export { generatePpcFilePath, generateEmsOutFilePath, deleteEmsFileIfExists };
