import { eq } from "drizzle-orm" import { db } from "@/lib/db" import { profiles } from "@/lib/db/schema" import type { Plan } from "@/types" // Applies PayPal subscription/order outcomes to a profile. Shared by the return // handler (synchronous, on approval redirect) and the webhook (async, for // renewals/cancellations). Both are idempotent. const RECURRING: ReadonlyArray = ["pro", "landlord"] export async function fulfillSubscription( userId: string, plan: string, subscriptionId: string, nextBillingTime?: string | null, status = "active", ): Promise { if (!RECURRING.includes(plan as Plan)) return await db .update(profiles) .set({ plan: plan as Plan, subscription_status: status, paypal_subscription_id: subscriptionId, billing_provider: "paypal", plan_expires_at: nextBillingTime ?? null, }) .where(eq(profiles.id, userId)) } export async function fulfillLifetime(userId: string): Promise { await db .update(profiles) .set({ plan: "lifetime", subscription_status: "active", billing_provider: "paypal" }) .where(eq(profiles.id, userId)) } /** Downgrade/mark a profile by its PayPal subscription id (cancel/expire/suspend). */ export async function markPaypalSubscriptionInactive( subscriptionId: string, status: string, downgrade: boolean, ): Promise { await db .update(profiles) .set( downgrade ? { subscription_status: status, plan: "starter", paypal_subscription_id: null, plan_expires_at: null } : { subscription_status: status }, ) .where(eq(profiles.paypal_subscription_id, subscriptionId)) }