import { NextRequest, NextResponse } from "next/server";
import { stripe } from "@/lib/stripe";
import { prisma } from "@/lib/db";
import type Stripe from "stripe";

export const runtime = "nodejs";
// IMPORTANT: must read raw body for signature verification.
export const dynamic = "force-dynamic";

export async function POST(req: NextRequest) {
  const sig = req.headers.get("stripe-signature");
  const secret = process.env.STRIPE_WEBHOOK_SECRET;
  if (!sig || !secret) {
    return NextResponse.json(
      { error: "Missing signature or webhook secret" },
      { status: 400 },
    );
  }

  const body = await req.text(); // raw body, required by Stripe verification
  let event: Stripe.Event;
  try {
    event = stripe.webhooks.constructEvent(body, sig, secret);
  } catch (err) {
    return NextResponse.json(
      { error: "Signature verification failed" },
      { status: 400 },
    );
  }

  if (event.type === "payment_intent.succeeded") {
    const pi = event.data.object as Stripe.PaymentIntent;
    const donation = await prisma.donation.findUnique({
      where: { stripePaymentIntentId: pi.id },
    });
    if (donation && donation.status === "PENDING") {
      // Mark payment confirmed; status remains PENDING until admin approval.
      // (We don't reuse status for "paid"; status reflects moderation.)
      // Add a note so admin sees payment confirmed.
      await prisma.donation.update({
        where: { id: donation.id },
        data: {
          notes: `Stripe payment confirmed at ${new Date().toISOString()}`,
        },
      });
    }
  }

  return NextResponse.json({ received: true });
}
