import { NextResponse } from "next/server"; import { assertAgencyAdmin, getRouteAgencyContextOrThrow } from "@/lib/agency"; import { env } from "@/lib/env"; import { getStripeClient } from "@/lib/stripe"; import { createSupabaseRouteClient } from "@/lib/supabase/route"; export async function POST() { try { const context = await getRouteAgencyContextOrThrow(); assertAgencyAdmin(context); if (!env.stripePriceId) { throw new Error("STRIPE_PRICE_ID is not configured"); } const stripe = getStripeClient(); const supabase = createSupabaseRouteClient(); const { data: billing, error: billingError } = await supabase .from("billing_accounts") .select("id, stripe_customer_id") .eq("agency_id", context.agencyId) .maybeSingle(); if (billingError) throw billingError; let customerId = billing?.stripe_customer_id ?? null; if (!customerId) { const customer = await stripe.customers.create({ metadata: { agency_id: context.agencyId, }, }); customerId = customer.id; const upsertPayload = { agency_id: context.agencyId, stripe_customer_id: customerId, }; if (billing?.id) { await supabase.from("billing_accounts").update(upsertPayload).eq("id", billing.id); } else { await supabase.from("billing_accounts").insert(upsertPayload); } } const session = await stripe.checkout.sessions.create({ mode: "subscription", customer: customerId, line_items: [{ price: env.stripePriceId, quantity: 1 }], success_url: `${env.appUrl}/dashboard?checkout=success`, cancel_url: `${env.appUrl}/dashboard?checkout=cancelled`, metadata: { agency_id: context.agencyId, }, }); return NextResponse.json({ url: session.url }); } catch (error) { return NextResponse.json( { error: error instanceof Error ? error.message : "Failed to create checkout session" }, { status: 400 }, ); } }