import type { LoginStatus } from "@/data/schemas/auth";

import { getRouteAccess } from "./route-meta";
import { ROUTE_BUILDERS, ROUTES } from "./routes";

export function isAuthenticatedUser(loginStatus: LoginStatus): boolean {
  return loginStatus !== "notLoggedIn" && loginStatus !== "guest";
}

export function resolveAuthenticatedNavigation(input: {
  loginStatus: LoginStatus;
  targetUrl: string;
}): string {
  if (isAuthenticatedUser(input.loginStatus)) return input.targetUrl;
  return ROUTE_BUILDERS.authWithRedirect(input.targetUrl);
}

export function resolveRouteGuardRedirect(input: {
  loginStatus: LoginStatus;
  pathname: string;
  searchParams?: string;
}): string | null {
  const access = getRouteAccess(input.pathname);

  if (access === "session" && input.loginStatus === "notLoggedIn") {
    return ROUTES.splash;
  }

  if (access === "realUser" && !isAuthenticatedUser(input.loginStatus)) {
    return ROUTE_BUILDERS.authWithRedirect(
      buildCurrentUrl(input.pathname, input.searchParams),
    );
  }

  return null;
}

function buildCurrentUrl(pathname: string, searchParams?: string): string {
  if (!searchParams) return pathname;
  return `${pathname}?${searchParams}`;
}
