1import { headers } from "next/headers";
2import { db } from "@/lib/db";
3import { billingEvents, invoices } from "@/lib/schema";
4import { verifySignature } from "@/lib/billing";
5
6export async function POST(request: Request) {
7 const signature = (await headers()).get("stripe-signature");
8 const event = verifySignature(await request.text(), signature);
9
10 const [seen] = await db
11 .insert(billingEvents)
12 .values({ provider: "stripe", eventId: event.id, type: event.type })
13 .onConflictDoNothing()
14 .returning({ id: billingEvents.id });
15
16 if (!seen) return Response.json({ duplicate: true });
17
18 if (event.type === "invoice.paid") {
19 await db.insert(invoices).values(toInvoice(event)).onConflictDoNothing();
20 }
21
22 return Response.json({ received: true });
23}