const DEFAULT_AUTH_REDIRECT = "/compte";
const LOCAL_AUTH_ORIGIN = "https://stylunique.local";

export function normalizeAuthRedirect(value: string | null | undefined, fallback = DEFAULT_AUTH_REDIRECT) {
  const fallbackPath = fallback.startsWith("/") && !fallback.startsWith("//") ? fallback : DEFAULT_AUTH_REDIRECT;
  const rawValue = String(value || "").trim();

  if (!rawValue || !rawValue.startsWith("/") || rawValue.startsWith("//")) {
    return fallbackPath;
  }

  try {
    const url = new URL(rawValue, LOCAL_AUTH_ORIGIN);

    if (url.origin !== LOCAL_AUTH_ORIGIN) {
      return fallbackPath;
    }

    if (url.pathname === "/connexion" || url.pathname === "/inscription") {
      return fallbackPath;
    }

    return `${url.pathname}${url.search}${url.hash}`;
  } catch {
    return fallbackPath;
  }
}
