import { TokenKey } from "/@/utils/auth";
import { loadEnv } from "@build/index";
import CryptoJS from "crypto-js";
import router from "./../router";

const { VITE_SECRET_KEY } = loadEnv();
function changeToken(token: string) {
  if (!token) return;
  const encJson = CryptoJS.AES.encrypt(
    JSON.stringify({ token }),
    VITE_SECRET_KEY
  );
  const encData = CryptoJS.enc.Base64.stringify(
    CryptoJS.enc.Utf8.parse(encJson)
  );

  router.push("/accept?t=" + encData);
}

function listener(event) {
  const { key, newValue } = event;

  switch (key) {
    case TokenKey:
      changeToken(newValue);
      break;
  }
}

export const registerEvent = () => window.addEventListener("storage", listener);
