import { IpcMainEvent, shell } from "electron";
import log from "electron-log/main";
import { autoUpdater } from "electron-updater";
import { User } from "firebase/auth";
import errorTypeCheck from "../../util/errorTypeCheck";
import ipcTypes from "../../util/ipcTypes.json";
import client from "../graphql/graphql-client";
import {
  ActiveBodyshopQueryResult,
  MasterdataQueryResult,
  QUERY_ACTIVE_BODYSHOP_TYPED,
  QUERY_MASTERDATA_TYPED,
} from "../graphql/queries";
import Store from "../store/store";
import { checkForAppUpdatesContinuously } from "../util/checkForAppUpdates";
import { sendIpcToRenderer } from "../util/toRenderer";

const ipcMainHandleAuthStateChanged = async (
  _event: IpcMainEvent,
  user: User | null,
): Promise<void> => {
  Store.set("user", user);
  try {
    //Need to query the currently active shop, and store the metadata as well.
    //Also need to query the OP Codes for decoding reference.
    const activeBodyshop: ActiveBodyshopQueryResult = await client.request(
      QUERY_ACTIVE_BODYSHOP_TYPED,
    );

    Store.set("app.bodyshop", activeBodyshop.bodyshops[0]);

    const OpCodes: MasterdataQueryResult = await client.request(
      QUERY_MASTERDATA_TYPED,
      {
        key: `${activeBodyshop.bodyshops[0].region_config}_ciecaopcodes`,
      },
    );
    Store.set(
      "app.masterdata.opcodes",
      JSON.parse(OpCodes.masterdata[0]?.value),
    );
    log.debug("Received authentication state change from Renderer.", user);
    log.debug("Requery shop information & master data.");

    //Check for updates
    const convCo = activeBodyshop.bodyshops[0].convenient_company;
    if (convCo === "alpha") {
      autoUpdater.channel = "alpha";
      log.debug("Setting update channel to ALPHA channel.");
    } else if (convCo === "beta") {
      autoUpdater.channel = "beta";
      log.debug("Setting update channel to BETA channel.");
    }
  } catch (error) {
    log.error(
      "Error while querying active bodyshop or masterdata",
      errorTypeCheck(error),
    );
    sendIpcToRenderer(
      ipcTypes.toRenderer.general.showErrorMessage,
      "Error connecting to ImEX Online servers to get shop data. Please try again.",
    );
  }
  checkForAppUpdatesContinuously();
};

const ipMainHandleResetPassword = async (): Promise<void> => {
  shell.openExternal(
    import.meta.env.VITE_COMPANY === "IMEX"
      ? "https://imex.online/resetpassword"
      : "https://romeonline.io/resetpassword",
  );
};

export { ipcMainHandleAuthStateChanged, ipMainHandleResetPassword };
