import type { PrismaClient } from '@generated/prisma/client'; import type { BillingProviderId, Result } from '@gruperly/shared'; import { err, ok } from '@gruperly/shared'; import prisma from '@/lib/prisma'; import { SyncSubscription } from '../../lib'; import { type BillingProviderResolver, type BillingWebhookFailure, type BillingWebhookRequest, getBillingProvider, } from '../../providers'; export type { BillingWebhookFailure, BillingWebhookRequest } from '../../providers'; type HandleBillingWebhookDeps = { db?: Pick; providers?: BillingProviderResolver; sync?: Pick; }; /** Prisma's unique-constraint violation: this delivery was already processed. */ const UNIQUE_VIOLATION = 'P2002'; /** * Applies one provider notification about a Pro subscription. * * The provider adapter checks the signature and says which subscription the * notification is about; the subscription is then fetched again from the * provider and synced (`SyncSubscription`). The body is never trusted for a * status. If syncing fails the dedupe key is removed, so the provider's retry * gets another chance (same rule as the WhatsApp webhook). */ export class HandleBillingWebhook { constructor(private readonly deps: HandleBillingWebhookDeps = {}) {} async execute( providerId: BillingProviderId, request: BillingWebhookRequest, ): Promise> { const parsed = await (this.deps.providers ?? getBillingProvider)(providerId).parseWebhook(request); if (!parsed.ok) return parsed; const hint = parsed.value; if (!hint.externalId) return ok({ duplicate: false, applied: false }); const db = this.deps.db ?? prisma; const dedupe = hint.dedupeKey ? { source: hint.source, dedupeKey: hint.dedupeKey } : null; if (dedupe) { try { await db.billingWebhookEvent.create({ data: dedupe }); } catch (error) { if ((error as { code?: string }).code === UNIQUE_VIOLATION) { return ok({ duplicate: true, applied: false }); } throw error; } } const unburn = async () => { if (!dedupe) return; await db.billingWebhookEvent .delete({ where: { source_dedupeKey: dedupe } }) .catch(() => undefined); }; try { const synced = await (this.deps.sync ?? new SyncSubscription()).byExternalId( providerId, hint.externalId, hint.country, ); if (!synced.ok) { await unburn(); return err('sync_failed'); } return ok({ duplicate: false, applied: synced.value.synced }); } catch { await unburn(); return err('sync_failed'); } } }