import { getCurrentUser } from './api';

/** Safe internal path only (blocks open redirects). */
export function safeNextPath(raw: string | null | undefined, fallback = '/'): string {
  if (!raw || !raw.startsWith('/') || raw.startsWith('//')) return fallback;
  return raw;
}

export function loginHref(next?: string): string {
  if (!next || next === '/') return '/login';
  return `/login?next=${encodeURIComponent(next)}`;
}

/** Redirect to login with return path. Returns true if redirected. */
export function requireAuth(router: { replace: (href: string) => void }, nextPath: string): boolean {
  if (getCurrentUser()) return false;
  router.replace(loginHref(nextPath));
  return true;
}
