import { NextRequest, NextResponse } from "next/server";
import Stripe from "stripe";
import { prisma } from "@/lib/prisma";
import { getStripeSettings } from "@/lib/stripe";
import { sendBookingConfirmation } from "@/lib/mail";

export async function POST(request: NextRequest) {
  const settings = await getStripeSettings();
  if (!settings?.webhookSecret) {
    return NextResponse.json({ error: "Webhook secret not configured" }, { status: 503 });
  }

  const signature = request.headers.get("stripe-signature");
  const rawBody = await request.text();

  const stripe = new Stripe(settings.secretKey);
  let event: Stripe.Event;
  try {
    event = stripe.webhooks.constructEvent(rawBody, signature ?? "", settings.webhookSecret);
  } catch (err) {
    console.error("[stripe-webhook] signature verification failed", err);
    return NextResponse.json({ error: "Invalid signature" }, { status: 400 });
  }

  if (event.type === "checkout.session.completed") {
    const session = event.data.object as Stripe.Checkout.Session;
    const bookingId = session.metadata?.bookingId;
    if (bookingId) {
      const booking = await prisma.booking.findUnique({
        where: { id: bookingId },
        include: { service: true },
      });

      if (booking && booking.status !== "paid") {
        const updated = await prisma.booking.update({
          where: { id: bookingId },
          data: {
            status: "paid",
            stripePaymentIntentId:
              typeof session.payment_intent === "string" ? session.payment_intent : null,
            amountPaidCents: session.amount_total ?? booking.service.priceCents,
          },
        });

        try {
          await sendBookingConfirmation(updated, booking.service, settings.notificationEmail ?? null);
        } catch (err) {
          console.error("[stripe-webhook] failed to send confirmation email", err);
        }
      }
    }
  }

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