import { NextRequest, NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";
import Stripe from "stripe";
import { TaskStatus } from "@agent-bounty/contracts";

const stripe = process.env.STRIPE_SECRET_KEY ? new Stripe(process.env.STRIPE_SECRET_KEY, {
  apiVersion: "2026-05-27.dahlia",
}) : null;

export async function POST(request: NextRequest) {
  const payload = await request.text();
  const signature = request.headers.get("stripe-signature");

  if (!signature || !process.env.STRIPE_WEBHOOK_SECRET) {
    return NextResponse.json({ error: "Missing signature or webhook secret" }, { status: 400 });
  }

  let event: Stripe.Event;

  try {
    if (!stripe) {
      throw new Error("Stripe SDK is not initialized");
    }
    event = stripe.webhooks.constructEvent(
      payload,
      signature,
      process.env.STRIPE_WEBHOOK_SECRET
    );
  } catch (err: any) {
    console.error(`[Webhook Error]`, err.message);
    return NextResponse.json({ error: `Webhook Error: ${err.message}` }, { status: 400 });
  }

  try {
    if (event.type === "checkout.session.completed") {
      const session = event.data.object as Stripe.Checkout.Session;
      
      const task = await prisma.task.findFirst({
        where: { stripe_checkout_session_id: session.id }
      });

      if (!task) {
        console.error(`[Webhook] Task not found for session: ${session.id}`);
        return NextResponse.json({ received: true });
      }

      // Payment is authorized (Auth Hold)
      // Save the payment_intent_id and set status to OPEN
      await prisma.task.update({
        where: { id: task.id },
        data: {
          stripe_payment_intent_id: session.payment_intent as string,
          status: TaskStatus.OPEN
        }
      });
      
      console.log(`[Webhook] Task ${task.id} is now OPEN. Payment Intent: ${session.payment_intent}`);
    }

    return NextResponse.json({ received: true });
  } catch (error: any) {
    console.error("[Webhook Processing Error]", error);
    return NextResponse.json({ error: "Internal Error" }, { status: 500 });
  }
}
