import { afterEach, expect, test, vi } from "vitest";

import { redirectToLogin, setNavigate } from "./auth-redirect";

function stubLocation(pathname: string, search = "") {
  const assign = vi.fn();
  vi.stubGlobal("location", { pathname, search, assign });
  return assign;
}

afterEach(() => {
  setNavigate(null);
  vi.unstubAllGlobals();
});

test("uses the registered navigate to soft-redirect with reason + from", () => {
  const assign = stubLocation("/objects/abc", "?x=1");
  const navigate = vi.fn();
  setNavigate(navigate);

  redirectToLogin();

  expect(navigate).toHaveBeenCalledWith(
    "/login?reason=expired&from=%2Fobjects%2Fabc%3Fx%3D1",
    { replace: true },
  );
  expect(assign).not.toHaveBeenCalled();
});

test("falls back to a hard navigation when no navigate is registered", () => {
  const assign = stubLocation("/objects/abc");

  redirectToLogin();

  expect(assign).toHaveBeenCalledWith("/login?reason=expired&from=%2Fobjects%2Fabc");
});

test("does nothing when already on /login", () => {
  stubLocation("/login");
  const navigate = vi.fn();
  setNavigate(navigate);

  redirectToLogin();

  expect(navigate).not.toHaveBeenCalled();
});
