import { expect, test, vi } from "vitest";
import {
  buildLoginRedirectPath,
  isDocumentEntryTarget,
  locationToPath,
  redirectAfterLogin,
  resolveLoginRedirectTarget
} from "./loginRedirect.js";

test("builds login path with the full current path", () => {
  const loginPath = buildLoginRedirectPath({
    hash: "#summary",
    pathname: "/finance/",
    search: "?view=rechargeDetails&app=lalu"
  });

  expect(loginPath).toBe("/login?redirect=%2Ffinance%2F%3Fview%3DrechargeDetails%26app%3Dlalu%23summary");
});

test("resolves login redirect from query before router state", () => {
  const target = resolveLoginRedirectTarget({
    pathname: "/login",
    search: "?redirect=%2Ffinance%2F%3Fview%3Drecon",
    state: { from: { pathname: "/system/users", search: "?page=2" } }
  });

  expect(target).toBe("/finance/?view=recon");
});

test("falls back to router state and preserves search and hash", () => {
  const target = resolveLoginRedirectTarget({
    pathname: "/login",
    search: "",
    state: { from: { hash: "#role", pathname: "/system/users", search: "?page=2" } }
  });

  expect(target).toBe("/system/users?page=2#role");
});

test("rejects unsafe or looping redirect targets", () => {
  expect(resolveLoginRedirectTarget({ search: "?redirect=https%3A%2F%2Fevil.example%2Ffinance%2F" })).toBe("/overview");
  expect(resolveLoginRedirectTarget({ search: "?redirect=%2F%2Fevil.example%2Ffinance%2F" })).toBe("/overview");
  expect(resolveLoginRedirectTarget({ search: "?redirect=%2Flogin%3Fredirect%3D%252Ffinance%252F" })).toBe("/overview");
});

test("detects document entry targets", () => {
  expect(isDocumentEntryTarget("/finance/?view=overview")).toBe(true);
  expect(isDocumentEntryTarget("/databi/social/?view=funnel")).toBe(true);
  expect(isDocumentEntryTarget("/ops-center/")).toBe(true);
  expect(isDocumentEntryTarget("/overview")).toBe(false);
});

test("redirectAfterLogin reloads document entries and uses router navigation for admin routes", () => {
  const navigate = vi.fn();
  const targetWindow = { location: { replace: vi.fn() } };

  redirectAfterLogin("/finance/?view=rechargeDetails", navigate, targetWindow);
  expect(targetWindow.location.replace).toHaveBeenCalledWith("/finance/?view=rechargeDetails");
  expect(navigate).not.toHaveBeenCalled();

  redirectAfterLogin("/system/users?page=2", navigate, targetWindow);
  expect(navigate).toHaveBeenCalledWith("/system/users?page=2", { replace: true });
});

test("locationToPath returns an empty string for missing location", () => {
  expect(locationToPath(null)).toBe("");
});
