import { expect, test, vi } from "vitest"; import { createAlbumSyncHandler } from "./album-sync-handler"; const secret = "cron-secret-at-least-16-chars"; function post(handler: ReturnType, headers: Record) { return handler( new Request("http://portal.test/api/cron/album-sync", { method: "POST", headers, }), ); } test("runs the sync and reports the granted count with a valid bearer token", async () => { const applyAllRules = vi.fn().mockResolvedValue({ granted: 3 }); const handler = createAlbumSyncHandler({ applyAllRules, cronSecret: secret }); const response = await post(handler, { authorization: `Bearer ${secret}` }); expect(response.status).toBe(200); await expect(response.json()).resolves.toEqual({ granted: 3 }); expect(applyAllRules).toHaveBeenCalledTimes(1); }); test("rejects a missing or wrong bearer token without running the sync", async () => { const applyAllRules = vi.fn(); const handler = createAlbumSyncHandler({ applyAllRules, cronSecret: secret }); const missing = await post(handler, {}); const wrong = await post(handler, { authorization: "Bearer nope" }); expect(missing.status).toBe(403); expect(wrong.status).toBe(403); expect(applyAllRules).not.toHaveBeenCalled(); }); test("reports the endpoint as disabled when no cron secret is configured", async () => { const applyAllRules = vi.fn(); const handler = createAlbumSyncHandler({ applyAllRules, cronSecret: undefined }); const response = await post(handler, { authorization: `Bearer ${secret}` }); expect(response.status).toBe(404); expect(applyAllRules).not.toHaveBeenCalled(); }); test("maps sync failures to a retryable upstream error", async () => { const applyAllRules = vi.fn().mockRejectedValue(new Error("db down")); vi.spyOn(console, "error").mockImplementation(() => {}); const handler = createAlbumSyncHandler({ applyAllRules, cronSecret: secret }); const response = await post(handler, { authorization: `Bearer ${secret}` }); expect(response.status).toBe(503); await expect(response.json()).resolves.toEqual({ code: "SYNC_FAILED" }); vi.restoreAllMocks(); });