import { sanitizeRedirectPath } from "@/lib/authRedirect";
import { pageApiPathFromPathname } from "@/lib/pageSlug";
import { cmsPageFetch } from "@/lib/siteApi";

/** True when a published CMS page exists for this browser path (requires active session). */
export async function publishedPageExistsAtPath(pathname: string): Promise<boolean> {
  const apiPath = pageApiPathFromPathname(pathname);
  if (!apiPath) {
    return false;
  }
  const res = await cmsPageFetch(apiPath);
  return res.ok;
}

/**
 * After login, return the intended path only if that published page exists;
 * otherwise fall back to `/` (homepage if configured, else authenticated 404).
 */
export async function resolvePostLoginRedirect(intendedPath: string): Promise<string> {
  const safe = sanitizeRedirectPath(intendedPath);
  if (await publishedPageExistsAtPath(safe)) {
    return safe;
  }
  return "/";
}
