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 { default as Store, default as store } from "../store/store";
import { checkForAppUpdatesContinuously } from "../util/checkForAppUpdates";
import { getMainWindow, sendIpcToRenderer } from "../util/toRenderer";

const ipcMainHandleAuthStateChanged = async (
  _event: IpcMainEvent,
  user: User | null,
): Promise<void> => {
  Store.set("user", user);
  log.debug("Received authentication state change from Renderer.", user);
  await setReleaseChannel();
  checkForAppUpdatesContinuously();
};

async function setReleaseChannel() {
  try {
    //Need to query the currently active shop, and store the metadata as well.
    //Also need to query the OP Codes for decoding reference.
    await handleShopMetaDataFetch();
    //Check for updates
    const bodyshop = Store.get("app.bodyshop");
    if (bodyshop?.convenient_company?.toLowerCase() === "alpha") {
      autoUpdater.channel = "alpha";
      log.debug("Setting update channel to ALPHA channel.");
    } else if (bodyshop?.convenient_company?.toLowerCase() === "beta") {
      autoUpdater.channel = "beta";
      log.debug("Setting update channel to BETA channel.");
    } else {
      log.debug("Setting update channel to LATEST channel.");
    }
  } catch (error) {
    log.error(
      "Error while querying active bodyshop or master data",
      errorTypeCheck(error),
    );
    sendIpcToRenderer(
      ipcTypes.toRenderer.general.showErrorMessage,
      "Error connecting to ImEX Online servers to get shop data. Please try again.",
    );
  }
}

const handleShopMetaDataFetch = async (
  reloadWindow?: boolean,
): Promise<void> => {
  try {
    log.debug("Requery shop information & master data.");
    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),
    );
    if (reloadWindow) {
      const mainWindow = getMainWindow();
      if (mainWindow) {
        mainWindow.reload();
      }
    }
  } catch (error) {
    log.error("Error while fetching shop metadata", errorTypeCheck(error));
    throw error;
  }
};

const ipMainHandleResetPassword = async (): Promise<void> => {
  shell.openExternal(
    store.get("app.isTest")
      ? `${import.meta.env.VITE_FE_URL_TEST}/resetpassword`
      : `${import.meta.env.VITE_FE_URL}/resetpassword`,
  );
};

export {
  handleShopMetaDataFetch,
  ipcMainHandleAuthStateChanged,
  ipMainHandleResetPassword,
  setReleaseChannel,
};
