import type { UserRole } from "@/types";

const ALLOWED_REDIRECT_PREFIXES = [
  "/app",
  "/admin",
  "/onboarding",
  "/login",
  "/register",
] as const;

/**
 * Allow only same-origin relative paths under known app prefixes.
 * Blocks open redirects (//evil, /\\evil, javascript:, external URLs).
 */
export function safeRedirectPath(url: string | null | undefined): string {
  if (!url) return "/app/dashboard";

  let path = url.trim();
  try {
    path = decodeURIComponent(path);
  } catch {
    return "/app/dashboard";
  }

  if (
    !path.startsWith("/") ||
    path.startsWith("//") ||
    path.includes("://") ||
    path.includes("\\") ||
    path.includes("@") ||
    /[\x00-\x1f]/.test(path)
  ) {
    return "/app/dashboard";
  }

  const pathname = path.split("?")[0]?.split("#")[0] ?? "";
  const allowed = ALLOWED_REDIRECT_PREFIXES.some(
    (prefix) => pathname === prefix || pathname.startsWith(`${prefix}/`)
  );

  return allowed ? path : "/app/dashboard";
}

/** Only /login (optional safe query) — used by force-logout. */
export function safeLoginCallbackPath(url: string | null | undefined): string {
  if (!url) return "/login";

  let path = url.trim();
  try {
    path = decodeURIComponent(path);
  } catch {
    return "/login";
  }

  if (
    !path.startsWith("/login") ||
    path.startsWith("//") ||
    path.includes("://") ||
    path.includes("\\") ||
    path.includes("@")
  ) {
    return "/login";
  }

  const pathname = path.split("?")[0]?.split("#")[0] ?? "";
  if (pathname !== "/login") return "/login";

  return path;
}

/** Validate post-survey redirect URLs — blocks javascript: and other schemes. */
export function safeSurveyRedirectUrl(
  url: string | null | undefined
): string | null {
  if (!url?.trim()) return null;
  const trimmed = url.trim();
  if (trimmed.startsWith("/") && !trimmed.startsWith("//")) {
    return trimmed;
  }
  try {
    const parsed = new URL(trimmed);
    if (parsed.protocol === "http:" || parsed.protocol === "https:") {
      return parsed.href;
    }
  } catch {
    return null;
  }
  return null;
}

/** Default landing path after login/register based on role and workspace. */
export function getPostAuthRedirectPath(user: {
  role?: UserRole;
  workspaceId?: string | null;
}): string {
  if (user.role === "super_admin" && !user.workspaceId) {
    return "/admin/overview";
  }
  return user.workspaceId ? "/app/dashboard" : "/onboarding";
}
