import { NextRequest, NextResponse } from "next/server";
import { getPayPalCredentials, getPayPalAccessToken } from "../paypalCredentials";

export async function POST(req: NextRequest) {
  try {
    const { orderId } = await req.json();

    if (!orderId) {
      return NextResponse.json({ error: "Missing orderId" }, { status: 400 });
    }

    const creds = await getPayPalCredentials();
    const accessToken = await getPayPalAccessToken(creds);

    const captureRes = await fetch(
      `${creds.baseUrl}/v2/checkout/orders/${orderId}/capture`,
      {
        method: "POST",
        headers: {
          Authorization: `Bearer ${accessToken}`,
          "Content-Type": "application/json",
        },
      },
    );

    if (!captureRes.ok) {
      const err = await captureRes.json();
      return NextResponse.json(
        { error: err.message ?? "Capture failed" },
        { status: 500 },
      );
    }

    const capture = await captureRes.json();
    const captureId =
      capture.purchase_units?.[0]?.payments?.captures?.[0]?.id ?? orderId;

    return NextResponse.json({
      success: true,
      orderId: capture.id,
      captureId,
      status: capture.status,
    });
  } catch (err) {
    const message = err instanceof Error ? err.message : "Internal error";
    return NextResponse.json({ error: message }, { status: 500 });
  }
}
