import { describe, expect, it, vi } from "vitest"; import { createLagoBillingGateway, ensureActiveLagoSubscription, LagoBillingGatewayError, normalizeLagoApiUrl, redactLagoValue } from "./lago.js"; function jsonResponse(body: unknown, status = 200): Response { return new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json", }, }); } describe("LagoBillingGateway", () => { it("creates customers through the Lago API and maps the response", async () => { const fetchImpl = vi.fn(async () => jsonResponse({ customer: { lago_id: "lago_customer_1", external_id: "tenant_1", name: "ACME GmbH", email: "billing@example.test", currency: "EUR", created_at: "2026-07-04T00:00:00Z", }, }) ); const gateway = createLagoBillingGateway({ apiUrl: "https://lago.example.test/", apiKey: "secret_lago_key", fetchImpl, }); await expect( gateway.createCustomer({ tenantId: "tenant_1", name: "ACME GmbH", email: "billing@example.test", currency: "EUR", }) ).resolves.toEqual({ provider: "lago", externalId: "tenant_1", providerCustomerId: "lago_customer_1", name: "ACME GmbH", email: "billing@example.test", currency: "EUR", createdAt: "2026-07-04T00:00:00Z", }); expect(fetchImpl).toHaveBeenCalledWith( "https://lago.example.test/api/v1/customers", expect.objectContaining({ method: "POST", headers: expect.objectContaining({ authorization: "Bearer secret_lago_key", "content-type": "application/json", }), body: JSON.stringify({ customer: { external_id: "tenant_1", name: "ACME GmbH", email: "billing@example.test", currency: "EUR", }, }), }) ); }); it("creates plan subscriptions without storing seat count as unsupported Lago usage", async () => { const fetchImpl = vi.fn(async () => jsonResponse({ subscription: { lago_id: "lago_subscription_1", external_id: "sub_tenant_1_business", external_customer_id: "tenant_1", plan_code: "business", status: "active", name: "business (5 seats)", current_billing_period_started_at: "2026-07-01T00:00:00Z", current_billing_period_ending_at: "2026-08-01T00:00:00Z", created_at: "2026-07-04T00:00:00Z", }, }) ); const gateway = createLagoBillingGateway({ apiUrl: "https://lago.example.test", apiKey: "secret_lago_key", fetchImpl, }); const subscription = await gateway.createSubscription({ tenantId: "tenant_1", subscriptionExternalId: "sub_tenant_1_business", planCode: "business", seatQuantity: 5, subscriptionAt: new Date("2026-07-04T00:00:00Z"), paymentMethodType: "manual", consolidateInvoice: false, }); expect(subscription).toMatchObject({ provider: "lago", externalId: "sub_tenant_1_business", providerSubscriptionId: "lago_subscription_1", externalCustomerId: "tenant_1", planCode: "business", status: "active", }); const request = JSON.parse(String(fetchImpl.mock.calls[0]?.[1]?.body)); expect(request.subscription).toMatchObject({ external_customer_id: "tenant_1", external_id: "sub_tenant_1_business", plan_code: "business", billing_time: "anniversary", subscription_at: "2026-07-04T00:00:00.000Z", payment_method: { payment_method_type: "manual" }, consolidate_invoice: false, }); expect(request.subscription).not.toHaveProperty("seatQuantity"); }); it("reuses the exact active plan version for idempotent paid return and webhook races", async () => { const subscription = { provider: "lago" as const, externalId: "hgco_1", providerSubscriptionId: "lago_subscription_1", externalCustomerId: "tenant_1", planCode: "hg_price_swarm_123", status: "active" as const, name: "swarm (20 seats)", currentBillingPeriodStartedAt: "2026-08-01T00:00:00Z", currentBillingPeriodEndingAt: "2026-09-01T00:00:00Z", createdAt: "2026-08-01T00:00:00Z", }; const gateway = { getSubscription: vi.fn(async () => subscription), createSubscription: vi.fn(), } as unknown as Parameters[0]; const input = { tenantId: "tenant_1", subscriptionExternalId: "hgco_1", planCode: "hg_price_swarm_123", seatQuantity: 20, paymentMethodType: "manual" as const, consolidateInvoice: false, }; const [fromReturn, fromWebhook] = await Promise.all([ensureActiveLagoSubscription(gateway, input), ensureActiveLagoSubscription(gateway, input)]); expect(fromReturn.providerSubscriptionId).toBe("lago_subscription_1"); expect(fromWebhook.providerSubscriptionId).toBe("lago_subscription_1"); expect(gateway.getSubscription).toHaveBeenCalledTimes(2); expect(gateway.createSubscription).not.toHaveBeenCalled(); }); it("creates and assigns an immutable managed plan without premium plan overrides", async () => { const managedPlan = { code: "hg_price_2026_07_29_1_starter_annual_sepa_abcd1234", name: "Core · 4 Büro · 8 Baustelle · Speicher: +500 GB Speicher", invoiceDisplayName: "Core · 4 Büro · 8 Baustelle · Speicher: +500 GB Speicher", description: "Core · HiveGrid Katalog 2026-07-29.1", interval: "monthly" as const, amountCents: 38_170, currency: "EUR", payInAdvance: true, taxCodes: ["de-vat-19"], metadata: { hivegrid_catalog_version: "2026-07-29.1", hivegrid_resource_kind: "selected_price", }, }; const providerPlan = { plan: { code: managedPlan.code, name: managedPlan.name, invoice_display_name: managedPlan.invoiceDisplayName, description: managedPlan.description, interval: managedPlan.interval, amount_cents: managedPlan.amountCents, amount_currency: managedPlan.currency, pay_in_advance: managedPlan.payInAdvance, taxes: [{ code: "de-vat-19" }], metadata: managedPlan.metadata, }, }; const fetchImpl = vi .fn() .mockResolvedValueOnce(new Response("{}", { status: 404 })) .mockResolvedValueOnce(jsonResponse(providerPlan)) .mockResolvedValueOnce( jsonResponse({ subscription: { lago_id: "lago_subscription_1", external_id: "sub_tenant_1_core", external_customer_id: "tenant_1", plan_code: managedPlan.code, status: "active", name: "Acme GmbH · Core", current_billing_period_started_at: null, current_billing_period_ending_at: null, created_at: "2026-07-29T00:00:00Z", }, }) ); const gateway = createLagoBillingGateway({ apiUrl: "https://lago.example.test", apiKey: "secret_lago_key", fetchImpl, }); await expect( gateway.createSubscription({ tenantId: "tenant_1", subscriptionExternalId: "sub_tenant_1_core", planCode: "starter_annual_sepa", seatQuantity: 12, name: "Acme GmbH · Core", managedPlan, }) ).resolves.toMatchObject({ planCode: managedPlan.code, externalId: "sub_tenant_1_core", }); expect(fetchImpl.mock.calls.map((call) => [call[0], call[1]?.method])).toEqual([ [`https://lago.example.test/api/v1/plans/${managedPlan.code}`, "GET"], ["https://lago.example.test/api/v1/plans", "POST"], ["https://lago.example.test/api/v1/subscriptions", "POST"], ]); expect(JSON.parse(String(fetchImpl.mock.calls[1]?.[1]?.body))).toEqual({ plan: { name: managedPlan.name, code: managedPlan.code, invoice_display_name: managedPlan.invoiceDisplayName, description: managedPlan.description, interval: "monthly", amount_cents: 38_170, amount_currency: "EUR", pay_in_advance: true, tax_codes: ["de-vat-19"], metadata: { hivegrid_catalog_version: "2026-07-29.1", hivegrid_resource_kind: "selected_price", }, }, }); const subscriptionRequest = JSON.parse(String(fetchImpl.mock.calls[2]?.[1]?.body)); expect(subscriptionRequest.subscription.plan_code).toBe(managedPlan.code); expect(subscriptionRequest.subscription).not.toHaveProperty("plan_overrides"); }); it("activates only the pending subscription and keeps the paid commitment end", async () => { const pendingResponse = { subscription: { lago_id: "lago_pending_1", external_id: "checkout_1", external_customer_id: "tenant_1", plan_code: "swarm", status: "pending", name: "Swarm", current_billing_period_started_at: null, current_billing_period_ending_at: null, created_at: "2026-07-31T18:00:00Z", }, }; const activeResponse = { subscription: { ...pendingResponse.subscription, status: "active", current_billing_period_started_at: "2026-07-31T18:30:00Z", current_billing_period_ending_at: "2026-08-31T18:30:00Z", }, }; const fetchImpl = vi .fn() .mockResolvedValueOnce(jsonResponse(pendingResponse)) .mockResolvedValueOnce(jsonResponse(pendingResponse)) .mockResolvedValueOnce(jsonResponse(activeResponse)); const gateway = createLagoBillingGateway({ apiUrl: "https://lago.example.test", apiKey: "secret_lago_key", fetchImpl }); await expect( gateway.activatePendingSubscription(" checkout_1 ", new Date("2026-07-31T18:30:00Z"), new Date("2027-07-31T18:30:00Z")) ).resolves.toMatchObject({ externalId: "checkout_1", status: "active" }); expect(fetchImpl.mock.calls.map((call) => [call[0], call[1]?.method])).toEqual([ ["https://lago.example.test/api/v1/subscriptions/checkout_1?status=pending", "GET"], ["https://lago.example.test/api/v1/subscriptions/checkout_1?status=pending", "PUT"], ["https://lago.example.test/api/v1/subscriptions/checkout_1?status=active", "GET"], ]); expect(JSON.parse(String(fetchImpl.mock.calls[1]?.[1]?.body))).toEqual({ subscription: { status: "pending", subscription_at: "2026-07-31T18:30:00.000Z", ending_at: "2027-07-31T18:30:00.000Z", }, }); }); it("waits for the exact pending Lago version instead of accepting an older active plan version", async () => { vi.useFakeTimers(); const pendingResponse = { subscription: { lago_id: "lago_pending_2", external_id: "checkout_2", external_customer_id: "tenant_1", plan_code: "colony", status: "pending", name: "Colony", current_billing_period_started_at: null, current_billing_period_ending_at: null, created_at: "2026-07-31T18:00:00Z", }, }; const olderActiveResponse = { subscription: { ...pendingResponse.subscription, lago_id: "lago_active_old", plan_code: "swarm", status: "active", }, }; const exactActiveResponse = { subscription: { ...pendingResponse.subscription, status: "active", current_billing_period_started_at: "2026-07-31T18:30:00Z", current_billing_period_ending_at: "2026-08-31T18:30:00Z", }, }; const fetchImpl = vi .fn() .mockResolvedValueOnce(jsonResponse(pendingResponse)) .mockResolvedValueOnce(jsonResponse(pendingResponse)) .mockResolvedValueOnce(jsonResponse(olderActiveResponse)) .mockResolvedValueOnce(jsonResponse(exactActiveResponse)); const gateway = createLagoBillingGateway({ apiUrl: "https://lago.example.test", apiKey: "secret_lago_key", fetchImpl }); const activation = gateway.activatePendingSubscription("checkout_2", "2026-07-31T18:30:00Z"); await vi.runAllTimersAsync(); await expect(activation).resolves.toMatchObject({ providerSubscriptionId: "lago_pending_2", status: "active" }); expect(fetchImpl).toHaveBeenCalledTimes(4); vi.useRealTimers(); }); it("treats an already-active subscription activation as an idempotent replay", async () => { const activeResponse = { subscription: { lago_id: "lago_active_1", external_id: "checkout_1", external_customer_id: "tenant_1", plan_code: "swarm", status: "active", name: "Swarm", current_billing_period_started_at: "2026-07-31T18:30:00Z", current_billing_period_ending_at: "2026-08-31T18:30:00Z", created_at: "2026-07-31T18:00:00Z", }, }; const fetchImpl = vi .fn() .mockResolvedValueOnce(new Response("{}", { status: 404 })) .mockResolvedValueOnce(jsonResponse(activeResponse)); const gateway = createLagoBillingGateway({ apiUrl: "https://lago.example.test", apiKey: "secret_lago_key", fetchImpl }); await expect(gateway.activatePendingSubscription("checkout_1", "2026-07-31T18:30:00Z")).resolves.toMatchObject({ status: "active" }); expect(fetchImpl.mock.calls.map((call) => [call[0], call[1]?.method])).toEqual([ ["https://lago.example.test/api/v1/subscriptions/checkout_1?status=pending", "GET"], ["https://lago.example.test/api/v1/subscriptions/checkout_1?status=active", "GET"], ]); }); it("terminates only a pending checkout subscription", async () => { const fetchImpl = vi.fn(async () => jsonResponse({ subscription: { lago_id: "lago_pending_1", external_id: "checkout_1", external_customer_id: "tenant_1", plan_code: "swarm", status: "canceled", name: "Swarm", current_billing_period_started_at: null, current_billing_period_ending_at: null, created_at: "2026-07-31T18:00:00Z", }, }) ); const gateway = createLagoBillingGateway({ apiUrl: "https://lago.example.test", apiKey: "secret_lago_key", fetchImpl }); await expect(gateway.terminatePendingSubscription("checkout_1")).resolves.toMatchObject({ status: "canceled" }); expect(fetchImpl).toHaveBeenCalledWith( "https://lago.example.test/api/v1/subscriptions/checkout_1?status=pending", expect.objectContaining({ method: "DELETE" }) ); }); it("reuses an exact managed plan and rejects immutable price drift", async () => { const managedPlan = { code: "hg_price_starter_exact", name: "Core · 2 Büro · 5 Baustelle", invoiceDisplayName: "Core · 2 Büro · 5 Baustelle", description: "Core · HiveGrid Katalog 2026-07-29.1", interval: "monthly" as const, amountCents: 19_900, currency: "EUR", payInAdvance: true, taxCodes: ["de-vat-19"], metadata: { hivegrid_catalog_version: "2026-07-29.1" }, }; const providerPlan = { plan: { code: managedPlan.code, name: managedPlan.name, invoice_display_name: managedPlan.invoiceDisplayName, description: managedPlan.description, interval: managedPlan.interval, amount_cents: managedPlan.amountCents, amount_currency: managedPlan.currency, pay_in_advance: managedPlan.payInAdvance, taxes: [{ code: "de-vat-19" }], metadata: managedPlan.metadata, }, }; const subscriptionResponse = { subscription: { lago_id: "lago_subscription_exact", external_id: "sub_exact", external_customer_id: "tenant_1", plan_code: managedPlan.code, status: "active", name: managedPlan.name, current_billing_period_started_at: null, current_billing_period_ending_at: null, created_at: null, }, }; const fetchImpl = vi.fn().mockResolvedValueOnce(jsonResponse(providerPlan)).mockResolvedValueOnce(jsonResponse(subscriptionResponse)); const gateway = createLagoBillingGateway({ apiUrl: "https://lago.example.test", apiKey: "secret_lago_key", fetchImpl }); await expect( gateway.createSubscription({ tenantId: "tenant_1", subscriptionExternalId: "sub_exact", planCode: "starter", seatQuantity: 7, managedPlan, }) ).resolves.toMatchObject({ planCode: managedPlan.code }); expect(fetchImpl).toHaveBeenCalledTimes(2); expect(fetchImpl.mock.calls[0]?.[1]?.method).toBe("GET"); expect(fetchImpl.mock.calls[1]?.[1]?.method).toBe("POST"); const driftFetch = vi.fn(async () => jsonResponse({ plan: { ...providerPlan.plan, amount_cents: 19_901, }, }) ); const driftGateway = createLagoBillingGateway({ apiUrl: "https://lago.example.test", apiKey: "secret_lago_key", fetchImpl: driftFetch, }); await expect( driftGateway.createSubscription({ tenantId: "tenant_1", subscriptionExternalId: "sub_drift", planCode: "starter", seatQuantity: 7, managedPlan, }) ).rejects.toMatchObject({ code: "RESPONSE_INVALID", message: "Managed Lago plan conflicts with the requested immutable pricing.", }); expect(driftFetch).toHaveBeenCalledTimes(1); }); it("creates one-off invoices through a Lago add-on fee", async () => { const fetchImpl = vi.fn(async () => jsonResponse({ invoice: { lago_id: "invoice_setup_1", number: "LAG-SETUP-001", external_customer_id: "tenant_1", status: "finalized", payment_status: "pending", invoice_type: "one_off", currency: "EUR", total_amount_cents: 29999, issuing_date: "2026-07-16", file_url: null, }, }) ); const gateway = createLagoBillingGateway({ apiUrl: "https://lago.example.test", apiKey: "secret_lago_key", fetchImpl, }); await expect( gateway.createOneOffInvoice({ tenantId: " tenant_1 ", addOnCode: " portal_domain_setup ", amountCents: 29999, currency: "eur", quantity: 1, description: "Portal domain setup", taxCodes: ["de-vat-19"], }) ).resolves.toMatchObject({ providerInvoiceId: "invoice_setup_1", externalCustomerId: "tenant_1", invoiceType: "one_off", totalAmountCents: 29999, paymentStatus: "pending", }); expect(fetchImpl).toHaveBeenCalledWith( "https://lago.example.test/api/v1/invoices", expect.objectContaining({ method: "POST", body: JSON.stringify({ invoice: { external_customer_id: "tenant_1", currency: "EUR", fees: [ { add_on_code: "portal_domain_setup", units: 1, unit_amount_cents: 29999, tax_codes: ["de-vat-19"], description: "Portal domain setup", }, ], }, }), }) ); }); it("rejects invalid one-off invoice inputs before contacting Lago", async () => { const fetchImpl = vi.fn(); const gateway = createLagoBillingGateway({ apiUrl: "https://lago.example.test", apiKey: "secret_lago_key", fetchImpl }); await expect(gateway.createOneOffInvoice({ tenantId: "tenant_1", addOnCode: "setup", amountCents: 0, currency: "EUR" })).rejects.toMatchObject({ code: "CONFIG_INVALID", }); await expect(gateway.createOneOffInvoice({ tenantId: "tenant_1", addOnCode: " ", amountCents: 29999, currency: "EUR" })).rejects.toMatchObject({ code: "CONFIG_INVALID", }); await expect(gateway.createOneOffInvoice({ tenantId: "tenant_1", addOnCode: "setup", amountCents: 29999, currency: "EURO" })).rejects.toMatchObject({ code: "CONFIG_INVALID", }); await expect( gateway.createOneOffInvoice({ tenantId: "tenant_1", addOnCode: "setup", amountCents: 29999, currency: "EUR", taxCodes: ["de-vat-19", "de-vat-19"] }) ).rejects.toMatchObject({ code: "CONFIG_INVALID" }); expect(fetchImpl).not.toHaveBeenCalled(); }); it("reads invoice status with optional tenant filter", async () => { const fetchImpl = vi.fn(async () => jsonResponse({ invoices: [ { lago_id: "invoice_1", number: "LAG-001", external_customer_id: "tenant_1", status: "finalized", payment_status: "succeeded", invoice_type: "subscription", currency: "EUR", total_amount_cents: 4900, issuing_date: "2026-07-04", file_url: "https://files.example.test/invoice_1.pdf", billing_periods: [ { external_subscription_id: "checkout_1", lago_subscription_id: "lago_subscription_1", invoicing_reason: "subscription_periodic", }, ], }, ], }) ); const gateway = createLagoBillingGateway({ apiUrl: "https://lago.example.test", apiKey: "secret_lago_key", fetchImpl, }); await expect(gateway.listInvoices({ tenantId: "tenant_1", page: 2, perPage: 10 })).resolves.toEqual([ { provider: "lago", providerInvoiceId: "invoice_1", number: "LAG-001", externalCustomerId: "tenant_1", status: "finalized", paymentStatus: "succeeded", invoiceType: "subscription", currency: "EUR", totalAmountCents: 4900, issuingDate: "2026-07-04", fileUrl: "https://files.example.test/invoice_1.pdf", billingPeriods: [ { externalSubscriptionId: "checkout_1", providerSubscriptionId: "lago_subscription_1", invoicingReason: "subscription_periodic", }, ], subscriptionExternalIds: ["checkout_1"], subscriptionProviderIds: ["lago_subscription_1"], }, ]); expect(fetchImpl.mock.calls[0]?.[0]).toBe("https://lago.example.test/api/v1/invoices?external_customer_id=tenant_1&page=2&per_page=10"); }); it("reads an invoice detail with its exact subscription correlation", async () => { const fetchImpl = vi.fn(async () => jsonResponse({ invoice: { lago_id: "invoice_1", number: "LAG-001", external_customer_id: "tenant_1", status: "finalized", payment_status: "pending", invoice_type: "subscription", currency: "EUR", total_amount_cents: 4_900, issuing_date: "2026-08-01", file_url: null, billing_periods: [ { external_subscription_id: " checkout_1 ", lago_subscription_id: " lago_subscription_1 ", invoicing_reason: "subscription_starting", }, { external_subscription_id: "checkout_1", lago_subscription_id: "lago_subscription_1", invoicing_reason: "future_lago_reason", }, ], }, }) ); const gateway = createLagoBillingGateway({ apiUrl: "https://lago.example.test", apiKey: "secret_lago_key", fetchImpl, }); await expect(gateway.getInvoice("invoice_1")).resolves.toMatchObject({ providerInvoiceId: "invoice_1", billingPeriods: [ { externalSubscriptionId: "checkout_1", providerSubscriptionId: "lago_subscription_1", invoicingReason: "subscription_starting", }, { externalSubscriptionId: "checkout_1", providerSubscriptionId: "lago_subscription_1", invoicingReason: null, }, ], subscriptionExternalIds: ["checkout_1"], subscriptionProviderIds: ["lago_subscription_1"], }); expect(fetchImpl.mock.calls[0]?.[0]).toBe("https://lago.example.test/api/v1/invoices/invoice_1"); }); it("downloads an invoice and maps the generated file url", async () => { const fetchImpl = vi.fn(async () => jsonResponse({ invoice: { lago_id: "invoice_1", number: "LAG-001", status: "finalized", payment_status: "succeeded", invoice_type: "subscription", currency: "EUR", total_amount_cents: 4900, issuing_date: "2026-07-04", file_url: "https://files.example.test/invoice_1.pdf", customer: { external_id: "tenant_1", }, }, }) ); const gateway = createLagoBillingGateway({ apiUrl: "https://lago.example.test", apiKey: "secret_lago_key", fetchImpl, }); await expect(gateway.downloadInvoice("invoice_1")).resolves.toMatchObject({ providerInvoiceId: "invoice_1", externalCustomerId: "tenant_1", fileUrl: "https://files.example.test/invoice_1.pdf", }); expect(fetchImpl.mock.calls[0]?.[0]).toBe("https://lago.example.test/api/v1/invoices/invoice_1/download"); expect(fetchImpl.mock.calls[0]?.[1]).toMatchObject({ method: "POST" }); }); it("updates an invoice payment status", async () => { const fetchImpl = vi.fn(async () => jsonResponse({ invoice: { lago_id: "invoice_1", number: "LAG-001", external_customer_id: "tenant_1", status: "finalized", payment_status: "succeeded", invoice_type: "subscription", currency: "EUR", total_amount_cents: 99900, issuing_date: "2026-07-06", file_url: "https://files.example.test/invoice_1.pdf", }, }) ); const gateway = createLagoBillingGateway({ apiUrl: "https://lago.example.test", apiKey: "secret_lago_key", fetchImpl, }); await expect(gateway.updateInvoicePaymentStatus("invoice_1", "succeeded")).resolves.toMatchObject({ providerInvoiceId: "invoice_1", paymentStatus: "succeeded", }); expect(fetchImpl).toHaveBeenCalledWith( "https://lago.example.test/api/v1/invoices/invoice_1", expect.objectContaining({ method: "PUT", body: JSON.stringify({ invoice: { payment_status: "succeeded", }, }), }) ); }); it("returns null on 404 reads and throws clear errors for failed calls", async () => { const fetchImpl = vi.fn(async () => new Response("{}", { status: 404 })); const gateway = createLagoBillingGateway({ apiUrl: "https://lago.example.test", apiKey: "secret_lago_key", fetchImpl, }); await expect(gateway.getCustomer("tenant_missing")).resolves.toBeNull(); fetchImpl.mockResolvedValueOnce(new Response("{}", { status: 500 })); await expect(gateway.listInvoices()).rejects.toMatchObject({ name: "LagoBillingGatewayError", code: "REQUEST_FAILED", status: 500, message: "Lago request failed with status 500.", }); }); it("terminates active subscriptions and falls back to the required pending-status endpoint", async () => { const terminated = { subscription: { lago_id: "lago_subscription_1", external_id: "acquisition_1", external_customer_id: "tenant_1", plan_code: "customer_portal_monthly", status: "terminated", name: "Customer Portal", current_billing_period_started_at: null, current_billing_period_ending_at: null, created_at: null, }, }; const activeFetch = vi.fn(async () => jsonResponse(terminated)); const activeGateway = createLagoBillingGateway({ apiUrl: "https://lago.example.test", apiKey: "secret_lago_key", fetchImpl: activeFetch }); await expect(activeGateway.terminateSubscription(" acquisition_1 ")).resolves.toMatchObject({ status: "terminated" }); expect(activeFetch).toHaveBeenCalledWith("https://lago.example.test/api/v1/subscriptions/acquisition_1", expect.objectContaining({ method: "DELETE" })); const pendingFetch = vi .fn() .mockResolvedValueOnce(new Response("{}", { status: 405 })) .mockResolvedValueOnce(jsonResponse(terminated)); const pendingGateway = createLagoBillingGateway({ apiUrl: "https://lago.example.test", apiKey: "secret_lago_key", fetchImpl: pendingFetch }); await expect(pendingGateway.terminateSubscription("acquisition_1")).resolves.toMatchObject({ status: "terminated" }); expect(pendingFetch.mock.calls[1]?.[0]).toBe("https://lago.example.test/api/v1/subscriptions/acquisition_1?status=pending"); expect(pendingFetch.mock.calls[1]?.[1]).toMatchObject({ method: "DELETE" }); }); it("treats two termination 404s as an idempotent already-terminated result", async () => { const fetchImpl = vi.fn(async () => new Response("{}", { status: 404 })); const gateway = createLagoBillingGateway({ apiUrl: "https://lago.example.test", apiKey: "secret_lago_key", fetchImpl }); await expect(gateway.terminateSubscription("acquisition_1")).resolves.toBeNull(); expect(fetchImpl).toHaveBeenCalledTimes(2); }); it("rejects invalid configuration and invalid response shapes", async () => { expect(() => normalizeLagoApiUrl("file:///tmp/lago")).toThrow(LagoBillingGatewayError); expect(() => createLagoBillingGateway({ apiUrl: "https://lago.example.test", apiKey: " " })).toThrow(LagoBillingGatewayError); const gateway = createLagoBillingGateway({ apiUrl: "https://lago.example.test", apiKey: "secret_lago_key", fetchImpl: vi.fn(async () => jsonResponse({ customer: { external_id: "tenant_1" } })), }); await expect(gateway.createCustomer({ tenantId: "tenant_1", name: "Tenant" })).rejects.toMatchObject({ code: "RESPONSE_INVALID", message: "Lago response shape is invalid.", }); }); it("redacts Lago IDs and tokens for diagnostics", () => { expect(redactLagoValue("secret_lago_key_123456")).toBe("secr…3456"); expect(redactLagoValue("short")).toBe("[redacted]"); expect(redactLagoValue(undefined)).toBeNull(); }); });