const ACCESS_TOKEN = "BMAHRISUSER_KEYCLOAK_IDENTITY";
const key_C_Config = {
  url_Logout: import.meta.env.VITE_URL_SSO,
  landing_PageUrl: import.meta.env.VITE_URL_LANDING,
};
interface AuthResponse {
  access_token: string;
  expires_in: number;
  refresh_token: string;
}

const authenticated = async () => ((await getToken()) ? true : false);

async function setAuthen(r: AuthResponse, val: string, url?: string) {
  if (r && r.access_token) {
    await setCookie(ACCESS_TOKEN, r.access_token, r.expires_in);
    setCookie("SSO", val, r.expires_in);
    window.location.href = url ? encodeURI(url) : "/";
  }
}

async function logout(force: boolean = false) {
  if (!force) {
    await deleteCookie(ACCESS_TOKEN);
    window.location.href = key_C_Config.url_Logout;
  } else {
    const currentUrl = window.location.href;
    const loginUrl = `${
      key_C_Config.landing_PageUrl
    }?system=user&redirectUrl=${encodeURIComponent(currentUrl)}`;
    window.location.href = loginUrl;
  }
}

async function getToken() {
  return getCookie(ACCESS_TOKEN);
}
// 2024-08-29T02:55:13.000Z
async function setCookie(name: string, value: any, time: number) {
  let expires = "";
  if (time) {
    const date = new Date();
    date.setTime(date.getTime() + time * 1000);
    // date.setTime(date.getTime() + days * 24 * 60 * 60 * 1000);
    expires = "; expires=" + date.toUTCString();
  }
  document.cookie = name + "=" + (value || "") + expires + "; path=/";
}

function getCookie(name: string) {
  const nameEQ = name + "=";
  const ca = document.cookie.split(";");
  for (let i = 0; i < ca.length; i++) {
    let c = ca[i];
    while (c.charAt(0) == " ") c = c.substring(1, c.length);
    if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
  }
  return null;
}

async function deleteCookie(name: string) {
  document.cookie = `${name}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;`;
}

async function tokenParsed() {
  const token = await getCookie(ACCESS_TOKEN);
  if (!token) {
    return null;
  }
  const base64Url = token.split(".")[1];
  const base64 = base64Url.replace(/-/g, "+").replace(/_/g, "/");
  const jsonPayload = decodeURIComponent(
    window
      .atob(base64)
      .split("")
      .map(function (c) {
        return "%" + ("00" + c.charCodeAt(0).toString(16)).slice(-2);
      })
      .join("")
  );

  return JSON.parse(jsonPayload);
}

async function redirectToLandingPage() {
  await deleteCookie(ACCESS_TOKEN);
  window.location.href = key_C_Config.landing_PageUrl;
}

async function logoutSSO() {
  await deleteCookie(ACCESS_TOKEN);
  window.location.href = key_C_Config.landing_PageUrl + `/logout`;
}

export {
  getToken,
  authenticated,
  logout,
  setAuthen,
  tokenParsed,
  getCookie,
  redirectToLandingPage,
  logoutSSO,
};
