import { NextResponse } from "next/server" import { eq } from "drizzle-orm" import { db } from "@/lib/db" import { profiles } from "@/lib/db/schema" import { getSessionUser } from "@/lib/session" import { paypalConfigured } from "@/lib/paypal/client" import { getPaypalPlanId } from "@/lib/paypal/plans" import { createSubscription, createOrder } from "@/lib/paypal/checkout" import { PLAN_AMOUNTS } from "@/lib/stripe/plans" const RECURRING = new Set(["pro", "landlord"]) // Start a PayPal checkout for a plan upgrade and return the approval URL. // Recurring plans → Subscriptions API; lifetime → one-time Orders API. export async function POST(request: Request) { if (!paypalConfigured()) { return NextResponse.json({ error: "PayPal is not configured" }, { status: 400 }) } const user = await getSessionUser() if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 }) const { plan, interval } = (await request.json().catch(() => ({}))) as { plan?: string interval?: "month" | "year" } if (!plan || (plan !== "lifetime" && !RECURRING.has(plan))) { return NextResponse.json({ error: "Invalid plan" }, { status: 400 }) } const appUrl = process.env.NEXT_PUBLIC_APP_URL! const cancelUrl = `${appUrl}/settings/billing?canceled=true` try { if (plan === "lifetime") { const { approveUrl } = await createOrder({ amount: PLAN_AMOUNTS.lifetime, userId: user.id, plan: "lifetime", returnUrl: `${appUrl}/api/paypal/return?type=order`, cancelUrl, }) if (!approveUrl) throw new Error("PayPal did not return an approval URL") return NextResponse.json({ url: approveUrl }) } const billingInterval = interval === "year" ? "year" : "month" const planId = getPaypalPlanId(plan as "pro" | "landlord", billingInterval) if (!planId) { return NextResponse.json({ error: "That plan isn't available on PayPal yet." }, { status: 400 }) } const profile = await db.query.profiles.findFirst({ where: eq(profiles.id, user.id), columns: { email: true }, }) const { approveUrl } = await createSubscription({ planId, userId: user.id, plan, email: profile?.email ?? user.email, returnUrl: `${appUrl}/api/paypal/return?type=subscription`, cancelUrl, }) if (!approveUrl) throw new Error("PayPal did not return an approval URL") return NextResponse.json({ url: approveUrl }) } catch (e) { return NextResponse.json( { error: (e as Error).message || "PayPal checkout failed" }, { status: 502 } ) } }