import type { PrismaClient, SubscriptionStatus } from '@generated/prisma/client'; import type { ProblemDetails, Result } from '@gruperly/shared'; import { err, ok } from '@gruperly/shared'; import { noActiveSubscriptionProblem } from '@/http/problem-builders'; import prisma from '@/lib/prisma'; import { subscriptionRefOf } from '../../lib'; import { type BillingProviderResolver, getBillingProvider, toBillingProblem } from '../../providers'; type CancelSubscriptionDeps = { db?: Pick; providers?: BillingProviderResolver; }; /** * Stops the monthly charge with the provider that collects it. `paidThrough` * stays: the professor keeps Pro until the end of what they already paid * (plus the grace period). */ export class CancelSubscription { constructor(private readonly deps: CancelSubscriptionDeps = {}) {} async execute(userId: string): Promise> { const db = this.deps.db ?? prisma; const subscription = await db.billingSubscription.findUnique({ where: { userId } }); if ( !subscription || (!subscription.externalId && !subscription.checkoutRef) || subscription.status === 'CANCELLED' ) { return err(noActiveSubscriptionProblem()); } try { await (this.deps.providers ?? getBillingProvider)(subscription.provider).cancel( subscriptionRefOf(subscription), ); } catch (error) { return err(toBillingProblem(error)); } await db.billingSubscription.update({ where: { id: subscription.id }, data: { status: 'CANCELLED', nextPaymentDate: null }, }); return ok({ status: 'CANCELLED' }); } }