import { describe, expect, test, vi } from "vitest";
import { redirectSubsystemEntry } from "../../../vite.config.js";

describe("external-admin Vite entry routing", () => {
  test("redirects the bare subsystem path and preserves the app query", () => {
    const req = { url: "/external-admin?app=fami" };
    const res = responseStub();
    const next = vi.fn();

    redirectSubsystemEntry(req, res, next);

    expect(res.statusCode).toBe(301);
    expect(res.setHeader).toHaveBeenCalledWith("Location", "/external-admin/?app=fami");
    expect(res.end).toHaveBeenCalled();
    expect(next).not.toHaveBeenCalled();
  });

  test("rewrites a BrowserRouter deep link to the isolated HTML document", () => {
    const req = { url: "/external-admin/organization/hosts?from=test" };
    const res = responseStub();
    const next = vi.fn();

    redirectSubsystemEntry(req, res, next);

    expect(req.url).toBe("/external-admin/index.html?from=test");
    expect(next).toHaveBeenCalledTimes(1);
    expect(res.end).not.toHaveBeenCalled();
  });

  test("does not rewrite source module requests", () => {
    const req = { url: "/external-admin/src/main.jsx" };
    const next = vi.fn();

    redirectSubsystemEntry(req, responseStub(), next);

    expect(req.url).toBe("/external-admin/src/main.jsx");
    expect(next).toHaveBeenCalledTimes(1);
  });
});

function responseStub() {
  return { end: vi.fn(), setHeader: vi.fn(), statusCode: 200 };
}
