import { describe, it, expect, vi, beforeEach } from "vitest"; // Override the global setup.ts mock for keys — we need the REAL implementation vi.unmock("../services/keys.js"); // Keep db mocked (setup.ts already does this, but be explicit about our mock) vi.mock("../services/db.js", () => ({ default: { query: vi.fn(), connect: vi.fn(), on: vi.fn(), end: vi.fn() }, pool: { query: vi.fn(), connect: vi.fn(), on: vi.fn(), end: vi.fn() }, queryWithRetry: vi.fn().mockResolvedValue({ rows: [], rowCount: 0 }), connectWithRetry: vi.fn().mockResolvedValue(undefined), initDatabase: vi.fn().mockResolvedValue(undefined), cleanupStaleData: vi.fn(), isTransientError: vi.fn(), })); vi.mock("../services/logger.js", () => ({ default: { info: vi.fn(), error: vi.fn(), warn: vi.fn(), debug: vi.fn() }, })); import { queryWithRetry } from "../services/db.js"; import { downgradeByCustomer } from "../services/keys.js"; const mockQuery = vi.mocked(queryWithRetry); describe("downgradeByCustomer DB fallback (BUG-106)", () => { beforeEach(() => { vi.clearAllMocks(); }); it("returns true and updates DB when key is NOT in cache but IS in DB", async () => { mockQuery .mockResolvedValueOnce({ rows: [ { key: "df_pro_abc123", tier: "pro", email: "user@example.com", created_at: "2026-01-01T00:00:00.000Z", stripe_customer_id: "cus_123", }, ], rowCount: 1, } as any) .mockResolvedValueOnce({ rows: [], rowCount: 1 } as any); // UPDATE const result = await downgradeByCustomer("cus_123"); expect(result).toBe(true); expect(mockQuery).toHaveBeenCalledWith( expect.stringContaining("SELECT"), expect.arrayContaining(["cus_123"]) ); expect(mockQuery).toHaveBeenCalledWith( expect.stringContaining("UPDATE"), expect.arrayContaining(["cus_123"]) ); }); it("returns false when key is NOT in cache AND NOT in DB", async () => { mockQuery.mockResolvedValueOnce({ rows: [], rowCount: 0 } as any); const result = await downgradeByCustomer("cus_nonexistent"); expect(result).toBe(false); expect(mockQuery).toHaveBeenCalledWith( expect.stringContaining("SELECT"), expect.arrayContaining(["cus_nonexistent"]) ); const updateCalls = mockQuery.mock.calls.filter((c) => (c[0] as string).includes("UPDATE") ); expect(updateCalls).toHaveLength(0); }); });