import type { ReadonlyURLSearchParams } from "next/navigation";

export function getSafeRedirect(candidate?: string | null, fallback = "/account"): string {
  const dest = (candidate ?? "").trim();
  if (!dest) return fallback;
  if (!dest.startsWith("/")) return fallback;
  if (dest.startsWith("//")) return fallback;
  if (dest.startsWith("http://") || dest.startsWith("https://")) return fallback;
  return dest;
}

export function getPostLoginRedirect(
  searchParams: ReadonlyURLSearchParams,
  override?: string | null
): string {
  const candidate = override || searchParams.get("next") || searchParams.get("redirect");
  return getSafeRedirect(candidate, "/account");
}
