const redirectParam = "redirect";
const defaultRedirectTarget = "/overview";
const documentEntryPrefixes = ["/finance", "/databi", "/ops-center", "/money"];

export function locationToPath(location) {
  if (!location?.pathname) {
    return "";
  }
  return `${location.pathname}${location.search || ""}${location.hash || ""}`;
}

export function buildLoginRedirectPath(location) {
  const target = normalizeRedirectTarget(locationToPath(location));
  if (!target) {
    return "/login";
  }
  return `/login?${redirectParam}=${encodeURIComponent(target)}`;
}

export function resolveLoginRedirectTarget(location, fallback = defaultRedirectTarget) {
  const queryTarget = new URLSearchParams(location?.search || "").get(redirectParam);
  return normalizeRedirectTarget(queryTarget) || normalizeRedirectTarget(locationToPath(location?.state?.from)) || fallback;
}

export function isDocumentEntryTarget(target) {
  const normalized = normalizeRedirectTarget(target);
  if (!normalized) {
    return false;
  }
  const { pathname } = new URL(normalized, currentOrigin());
  return documentEntryPrefixes.some((prefix) => pathname === prefix || pathname.startsWith(`${prefix}/`));
}

export function redirectAfterLogin(target, navigate, targetWindow = window) {
  const normalized = normalizeRedirectTarget(target) || defaultRedirectTarget;
  if (isDocumentEntryTarget(normalized)) {
    // Subsystems are separate HTML entries; SPA navigation would hit the admin fallback route.
    targetWindow.location.replace(normalized);
    return;
  }
  navigate(normalized, { replace: true });
}

function normalizeRedirectTarget(value) {
  const raw = String(value || "").trim();
  if (!raw || raw.startsWith("//")) {
    return "";
  }

  let url;
  try {
    url = new URL(raw, currentOrigin());
  } catch {
    return "";
  }

  if (url.origin !== currentOrigin()) {
    return "";
  }

  const target = `${url.pathname}${url.search}${url.hash}`;
  if (!target.startsWith("/") || isLoginTarget(target)) {
    return "";
  }
  return target;
}

function isLoginTarget(target) {
  return new URL(target, currentOrigin()).pathname === "/login";
}

function currentOrigin() {
  return globalThis.window?.location?.origin || "http://localhost";
}
