// Pure utility — no Next.js or Supabase imports.
// Only allow same-origin relative redirect targets.
// Anything that could be parsed as an absolute URL
// (e.g. `//evil.com`, `https://evil.com`, `/\evil.com`)
// falls back to the default landing page to prevent open-redirect phishing.
//
// Exported so it can be unit-tested independently (Batch 6 / SEC-004).

export const SAFE_REDIRECT_FALLBACK = '/projektanlage'

/**
 * Returns `path` when it is a safe same-origin relative URL, otherwise
 * returns the fallback path.
 *
 * A safe path must start with a single `/` followed by a character that is
 * neither `/` nor `\`.  This rejects:
 *   - protocol-relative URLs  (`//evil.com`)
 *   - absolute URLs            (`https://…`)
 *   - backslash tricks         (`/\evil.com`, `\/evil.com`)
 *   - null / empty             (returns fallback)
 */
export function safeRedirectPath(raw: string | null | undefined): string {
  if (!raw || !raw.trim()) return SAFE_REDIRECT_FALLBACK
  if (!/^\/[^/\\]/.test(raw)) return SAFE_REDIRECT_FALLBACK
  return raw
}
