import { getInstanceConfig } from "@/instance-config";
import { ROUTES } from "@/router/routes";

const AUTH_DISABLED = false;

const PUBLIC_ROUTES = [
  "/u/", // User profile pages (dynamic)
  "/memos/", // Individual memo detail pages (dynamic)
] as const;

const PRIVATE_ROUTES = [
  ROUTES.ROOT,
  ROUTES.EXPLORE, // Now protected with Clerk
  ROUTES.ATTACHMENTS,
  ROUTES.INBOX,
  ROUTES.ARCHIVED,
  ROUTES.SETTING,
] as const;

function isPublicRoute(path: string): boolean {
  return PUBLIC_ROUTES.some((route) => path.startsWith(route));
}

function isPrivateRoute(path: string): boolean {
  return PRIVATE_ROUTES.includes(path as (typeof PRIVATE_ROUTES)[number]);
}

/**
 * Redirects to auth page if user is not authenticated.
 * Note: This is a fallback - most routes are now protected by ProtectedRoute component.
 */
export function redirectOnAuthFailure(): void {
  if (AUTH_DISABLED) {
    return;
  }

  const currentPath = window.location.pathname;

  // Don't redirect if it's a public route
  if (isPublicRoute(currentPath)) {
    return;
  }

  const disallowPublicVisibility = getInstanceConfig().memoRelatedSetting.disallowPublicVisibility;
  const target = ROUTES.AUTH;

  // Only redirect if it's a private route or disallowPublicVisibility is enabled
  if (disallowPublicVisibility || isPrivateRoute(currentPath)) {
    window.location.replace(target);
  }
}
