import { SupabaseClient } from '@supabase/supabase-js'; import { getLogger } from '@kit/shared/logger'; import { Database } from '@kit/supabase/database'; import { RecordChange, Tables } from '../record-change.type'; export class DatabaseWebhookRouterService { constructor(private readonly adminClient: SupabaseClient) {} async handleWebhook(body: RecordChange) { switch (body.table) { case 'invitations': { const payload = body as RecordChange; return this.handleInvitationsWebhook(payload); } case 'subscriptions': { const payload = body as RecordChange; return this.handleSubscriptionsWebhook(payload); } case 'accounts': { const payload = body as RecordChange; return this.handleAccountsWebhook(payload); } default: { const logger = await getLogger(); logger.warn( { table: body.table, }, 'No handler found for table', ); } } } private async handleInvitationsWebhook(body: RecordChange<'invitations'>) { const { AccountInvitationsWebhookService } = await import( '@kit/team-accounts/webhooks' ); const service = new AccountInvitationsWebhookService(this.adminClient); return service.handleInvitationWebhook(body.record); } private async handleSubscriptionsWebhook( body: RecordChange<'subscriptions'>, ) { const { BillingWebhooksService } = await import('@kit/billing-gateway'); const service = new BillingWebhooksService(); if (body.type === 'DELETE' && body.old_record) { return service.handleSubscriptionDeletedWebhook(body.old_record); } } private async handleAccountsWebhook(body: RecordChange<'accounts'>) { const { AccountWebhooksService } = await import( '@kit/team-accounts/webhooks' ); const service = new AccountWebhooksService(); if (body.type === 'DELETE' && body.old_record) { return service.handleAccountDeletedWebhook(body.old_record); } } }