const TAB_BAR_PAGES = ["/pages/map/map", "/pages/user/user"];

export function isAuthenticated(): boolean {
  return !!getApp<any>().globalData.token;
}

export function isTabBarPage(path: string): boolean {
  if (!path) return false;
  return TAB_BAR_PAGES.some((p) => path.indexOf(p) >= 0);
}

export function requireAuth(redirectUrl?: string): boolean {
  if (isAuthenticated()) {
    return true;
  }

  const pages = getCurrentPages();
  const currentPage = pages[pages.length - 1];
  if (currentPage && currentPage.route === "pages/login/login") {
    return false;
  }

  const redirect = redirectUrl
    ? `/${redirectUrl}`.replace(/^\/+/, "/")
    : `/${currentPage?.route || "pages/map/map"}`;

  uni.navigateTo({
    url: `/pages/login/login?redirect=${encodeURIComponent(redirect)}`,
  });

  return false;
}
