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

export async function POST(req: NextRequest) {
  try {
    const { amount, currency = "USD", itemName, quantity = 1 } = await req.json();

    if (!amount || isNaN(Number(amount))) {
      return NextResponse.json({ error: "Invalid amount" }, { status: 400 });
    }

    const creds = await getPayPalCredentials();
    const accessToken = await getPayPalAccessToken(creds);
    const value = Number(amount).toFixed(2);

    const orderRes = await fetch(`${creds.baseUrl}/v2/checkout/orders`, {
      method: "POST",
      headers: {
        Authorization: `Bearer ${accessToken}`,
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        intent: "CAPTURE",
        purchase_units: [
          {
            ...(itemName ? { description: String(itemName).slice(0, 127) } : {}),
            amount: {
              currency_code: currency,
              value,
              ...(itemName
                ? { breakdown: { item_total: { currency_code: currency, value } } }
                : {}),
            },
            ...(itemName
              ? {
                  items: [
                    {
                      name: String(itemName).slice(0, 127),
                      quantity: String(quantity),
                      unit_amount: { currency_code: currency, value },
                      category: "PHYSICAL_GOODS",
                    },
                  ],
                }
              : {}),
          },
        ],
      }),
    });

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

    const order = await orderRes.json();
    return NextResponse.json({ orderId: order.id });
  } catch (err) {
    const message = err instanceof Error ? err.message : "Internal error";
    return NextResponse.json({ error: message }, { status: 500 });
  }
}
