import { eq } from "drizzle-orm";
import { NextResponse } from "next/server";

import { getStripe } from "@/lib/billing/stripe";
import { handleStripeEvent } from "@/lib/billing/webhook";
import { db } from "@/lib/db";
import { stripeEvent } from "@/lib/db/schema";
import { env } from "@/lib/env";

export const runtime = "nodejs";

export async function POST(req: Request) {
  if (!env.STRIPE_WEBHOOK_SECRET) {
    console.error("[stripe-webhook] STRIPE_WEBHOOK_SECRET not configured");
    return NextResponse.json({ error: "Webhook secret not configured" }, { status: 503 });
  }

  const sig = req.headers.get("stripe-signature");
  if (!sig) return NextResponse.json({ error: "Missing stripe-signature" }, { status: 401 });

  const rawBody = await req.text();
  let event;
  try {
    event = getStripe().webhooks.constructEvent(rawBody, sig, env.STRIPE_WEBHOOK_SECRET);
  } catch (err) {
    console.error("[stripe-webhook] signature verification failed:", err);
    return NextResponse.json({ error: "Invalid signature" }, { status: 401 });
  }

  const inserted = await db
    .insert(stripeEvent)
    .values({ id: event.id, type: event.type })
    .onConflictDoNothing({ target: stripeEvent.id })
    .returning({ id: stripeEvent.id });
  if (inserted.length === 0) {
    return NextResponse.json({ status: "duplicate" }, { status: 200 });
  }

  try {
    await handleStripeEvent(event);
    return NextResponse.json({ status: "ok" }, { status: 200 });
  } catch (err) {
    console.error("[stripe-webhook] handler error for", event.type, err);
    await db.delete(stripeEvent).where(eq(stripeEvent.id, event.id));
    return NextResponse.json({ error: "Handler failed" }, { status: 500 });
  }
}
