const log = require("electron-log");
const axios = require("axios");
const path = require("path");
const { BrowserWindow } = require("electron");
const { default: ipcTypes } = require("../../src/ipc.types.commonjs");
const { promises: fsPromises } = require("fs");
const { autoUpdater } = require("electron-updater");
const { store } = require("../electron-store")

// Function to write job object to logs subfolder
async function writeJobToLogsFolder(job, fileName) {
  try {
    // Get the directory where electron-log stores its files
    const logFilePath = log.transports.file.getFile().path;
    const logsDir = path.dirname(logFilePath);

    // Create a subfolder for job objects
    const jobLogsDir = path.join(logsDir, "esjson");

    // Ensure the directory exists
    await fsPromises.mkdir(jobLogsDir, { recursive: true });

    // Write the job object as JSON
    const jobFilePath = path.join(jobLogsDir, `${fileName}.json`);
    await fsPromises.writeFile(jobFilePath, JSON.stringify(job, null, 2), "utf8");

    log.debug(`Job object written to: ${jobFilePath}`);
    console.log(`Job object written to: ${jobFilePath}`);
    return jobFilePath;
  } catch (error) {
    log.error("Error writing job object to logs folder:", error);
    throw error;
  }
}
async function ScrubEstimate({ job }) {
  //These are hard coded as they are not secure values and checking happens based on other values.
  //No secret or private information is exposed.
  const basicAuthUser = "Imex2";
  const basicAuthpassword = "Patrick";
  const currentChannel = autoUpdater.channel;
  let estimateScrubberUrl;
  switch (currentChannel) {
    case "alpha":
      estimateScrubberUrl = "https://4284-79287.el-alt.com"; //dev specific URL.
      break;
    case "beta":
      estimateScrubberUrl = "https://4284-79073.el-alt.com"; //Beta specific URL.
      break;
    default:
      estimateScrubberUrl = "https://insurtechtoolkit.com"; //Production route.
      break;
  }

  log.log(`Estimate Scrubber URL: [${currentChannel} |`, estimateScrubberUrl);
  const sendingEntityId = "87330f61-412b-4251-baaa-d026565b23c5";
  try {
    const esApiKey = job?.bodyshop?.es_api_key;
    //Perform data manipulation on the job object
    if (!job) {
      console.error("No job provided to ScrubEstimate");
      return;
    }

    let association_switch
    switch (store.get("ins_rule_set")) {
      case "MPI":
        association_switch = "ATAM";
        break;
      case "SGI":
        association_switch = "SAAR";
        break;
      default:
        association_switch = "ATAM";
        break;
    }

    //Set shop metrics
    job.sending_entity_id = sendingEntityId;
    job.sending_entity_accept_terms_of_use = true;
    job.association_switch = association_switch;
    job.rf_zip = job.bodyshop.zip_post;
    job.rf_ph1 = job.bodyshop.phone;
    job.g_ttl_amt = job.clm_total;
    job.source_system = "M"; //Requested by Steven.
    job.v_mileage = job.v_mileage?.toString() || "" //Requested by Steven to be a string.

    delete job.clm_total;
    delete job.bodyshop; //Bodyshop has to be passed through the object as we don't have access to the store here.

    //Adjust the rates field to be MAT_TYPE instead of MATL_TYPE
    if (job.rates && Array.isArray(job.rates)) {
      job.rates.forEach((rate) => {
        if (rate.MATL_TYPE) {
          rate.MAT_TYPE = rate.MATL_TYPE;
          delete rate.MATL_TYPE;
        }
      });
    }

    //Lower case the rates & totals
    if (job.rates && Array.isArray(job.rates)) {
      job.rates = job.rates.map((rate) => {
        const lowercasedRate = {};
        for (const [key, value] of Object.entries(rate)) {
          lowercasedRate[key.toLowerCase()] = value;
        }
        return lowercasedRate;
      });
    }

    if (job.totals && Array.isArray(job.totals)) {
      job.totals = job.totals.map((total) => {
        const lowercasedTotal = {};
        for (const [key, value] of Object.entries(total)) {
          lowercasedTotal[key.toLowerCase()] = value;
        }
        return lowercasedTotal;
      });
    }

    const fileName = `RPS-Scrub-${esApiKey}-${job.clm_no}-${Date.now()}`;

    // Write job object to logs subfolder
    try {
      await writeJobToLogsFolder(job, fileName);
    } catch (error) {
      log.error("Failed to write job to logs folder:", error);
      // Continue with the rest of the function even if this fails
    }

    const formData = new FormData();
    const jsonString = JSON.stringify(job);
    formData.append("file", new Blob([jsonString], { type: "application/json" }), `${fileName}.json`);

    const result = await axios.post(`${estimateScrubberUrl}/api/sendems`, formData, {
      auth: {
        username: basicAuthUser,
        password: basicAuthpassword
      },
      headers: { ...(formData.getHeaders ? formData.getHeaders() : {}), APIkey: esApiKey }
    });

    const resultPDFUrl = result?.data?.report_link;
    const reportIssueUrl = `https://insurtechtoolkit.com/pcontactUs.aspx?apiKey=${esApiKey}&file=${fileName}.json`
    // log.log("Estimate Scrubber Result:", result.data, resultPDFUrl);
    const b = BrowserWindow.getAllWindows()[0];
    b.webContents.send(ipcTypes.app.toRenderer.scrubResults, {
      jobid: job.id,
      items: result.data?.identified_item,
      pdfUrl: resultPDFUrl,
      reportIssueUrl
    });

    // const pdfWindow = new BrowserWindow({

    //     webPreferences: {
    //         plugins: true, // Enable PDF viewing
    //     },
    // });

    // pdfWindow.loadURL(resultPDFUrl);
    // pdfWindow.focus();
    return resultPDFUrl;
  } catch (error) {
    log.error("Error while scrubbing estimate:", error, error.stack);
    log.error("Error Response Data:", error.response?.data);
    const mainWindow = BrowserWindow.getAllWindows()[0];

    if (error.status === 400) {
      mainWindow.webContents.send(ipcTypes.app.toRenderer.scrubError, {
        message: error.response?.data || "Error encountered sending estimate to Estimate Scrubber."
      });
    } else if (error.status === 401) {
      mainWindow.webContents.send(ipcTypes.app.toRenderer.scrubError, {
        message: "Authentication with Estimate Scrubber failed." || error.response?.data
      });
    }
  }
}
exports.ScrubEstimate = ScrubEstimate;
