import { describe, it, expect, vi, beforeEach } from "vitest"; const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn(), getToken: vi.fn() })); vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi })); vi.mock("@/app/lib/server/session", () => ({ getToken: mocks.getToken })); import { GET, PUT } from "./route"; type Req = Parameters[0]; const ctx = (...path: string[]) => ({ params: Promise.resolve({ path: path.length ? path : undefined }) }); const req = (url: string, init?: RequestInit) => new Request(`http://localhost${url}`, init) as unknown as Req; beforeEach(() => { mocks.callMobileApi.mockReset(); mocks.getToken.mockReset(); mocks.getToken.mockResolvedValue("jwt-abc"); mocks.callMobileApi.mockResolvedValue({ ok: true, data: { ok: 1 } }); }); describe("/api/leads/[[...path]]", () => { it("returns 401 without a session", async () => { mocks.getToken.mockResolvedValue(null); const res = await GET(req("/api/leads"), ctx()); expect(res.status).toBe(401); expect(mocks.callMobileApi).not.toHaveBeenCalled(); }); it("forwards the list call (no path) with the query string", async () => { const res = await GET(req("/api/leads?q=ann&page=0&size=20"), ctx()); expect(res.status).toBe(200); expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/leads?q=ann&page=0&size=20", { token: "jwt-abc" }); }); it("forwards the detail GET and the PUT body", async () => { await GET(req("/api/leads/l-1"), ctx("l-1")); expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/leads/l-1", { token: "jwt-abc" }); await PUT(req("/api/leads/l-1", { method: "PUT", body: JSON.stringify({ name: "Ann" }) }), ctx("l-1")); expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/leads/l-1", { method: "PUT", body: { name: "Ann" }, token: "jwt-abc" }); }); it("rejects dot segments so the proxy cannot leave /api/admin/leads", async () => { const res = await GET(req("/api/leads/x"), ctx("..", "users")); expect(res.status).toBe(400); expect(mocks.callMobileApi).not.toHaveBeenCalled(); }); it("encodes path segments", async () => { await GET(req("/api/leads/a"), ctx("a/b")); expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/leads/a%2Fb", { token: "jwt-abc" }); }); it("passes upstream 404 with its code", async () => { mocks.callMobileApi.mockResolvedValue({ ok: false, error: "Lead not found", status: 404, code: "LEAD_NOT_FOUND" }); const res = await GET(req("/api/leads/zz"), ctx("zz")); expect(res.status).toBe(404); expect(((await res.json()) as Record).code).toBe("LEAD_NOT_FOUND"); }); });