import { NextResponse } from "next/server";
import Stripe from "stripe";
import { db } from "@/lib/db";
import { headers } from "next/headers";

const stripe = new Stripe(process.env.STRIPE_SECRET_KEY || 'sk_test_mock', {
  apiVersion: '2024-06-20' as any,
});

export async function POST(req: Request) {
  const body = await req.text();
  const signature = (await headers()).get("Stripe-Signature") as string;

  let event: Stripe.Event;

  try {
    event = stripe.webhooks.constructEvent(
      body,
      signature,
      process.env.STRIPE_WEBHOOK_SECRET!
    );
  } catch (error: any) {
    return NextResponse.json({ error: `Webhook Error: ${error.message}` }, { status: 400 });
  }

  const session = event.data.object as Stripe.Checkout.Session;

  if (event.type === 'checkout.session.completed') {
    const orderId = session.metadata?.orderId;
    const courseId = session.metadata?.courseId;
    const userId = session.metadata?.userId;

    if (orderId && courseId && userId) {
      // Payment successful - update everything in a transaction
      await db.$transaction(async (tx) => {
        // 1. Mark Order as COMPLETED
        await tx.order.update({
          where: { id: orderId },
          data: { status: "COMPLETED" }
        });

        // 2. Emit Invoice (e-Factura flow later)
        const order = await tx.order.findUnique({ where: { id: orderId } });
        if (order) {
            await tx.invoice.create({
            data: {
                invoiceNumber: Math.floor(Date.now() / 1000),
                orderId: order.id,
                totalAmount: order.totalAmount,
                taxAmount: 0,
                status: "ISSUED", // Because payment is complete
                pdfUrl: null
            }
            });
        }

        // 3. Grant Course Access (ACTIVE Enrollment)
        await tx.enrollment.upsert({
          where: { userId_courseId: { userId, courseId } },
          update: { status: "ACTIVE" },
          create: {
            userId,
            courseId,
            status: "ACTIVE"
          }
        });
      });
    }
  }

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