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

/**
 * Creates a PayPal order for the redirect (full-page) checkout flow.
 * PayPal redirects the buyer to the provided return_url / cancel_url after
 * they approve or cancel on paypal.com.
 *
 * Request body:
 *   amount     – total amount to charge (number)
 *   currency   – ISO-4217 code, e.g. "USD"  (default "USD")
 *   itemName   – product title shown on PayPal checkout (optional)
 *   quantity   – number of units (default 1)
 *   returnUrl  – absolute URL PayPal redirects to on success   (required)
 *   cancelUrl  – absolute URL PayPal redirects to on cancel    (required)
 *
 * Response:
 *   { paypalOrderId, approvalUrl }
 */
export async function POST(req: NextRequest) {
  try {
    const {
      amount,
      currency = "USD",
      itemName,
      returnUrl,
      cancelUrl,
    } = await req.json();

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

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

    const body = {
      intent: "CAPTURE",
      payment_source: {
        paypal: {
          experience_context: {
            brand_name: "Doliplay Marketplace",
            landing_page: "LOGIN",
            user_action: "PAY_NOW",
            return_url: returnUrl,
            cancel_url: cancelUrl,
          },
        },
      },
      purchase_units: [
        {
          ...(itemName
            ? { description: String(itemName).slice(0, 127) }
            : {}),
          amount: {
            currency_code: currency,
            value,
          },
          ...(itemName
            ? {
              soft_descriptor: String(itemName).slice(0, 22),
            }
            : {}),
        },
      ],
    };

    const orderRes = await fetch(`${creds.baseUrl}/v2/checkout/orders`, {
      method: "POST",
      headers: {
        Authorization: `Bearer ${accessToken}`,
        "Content-Type": "application/json",
        "PayPal-Request-Id": `doliplay-${Date.now()}`,
      },
      body: JSON.stringify(body),
    });

    if (!orderRes.ok) {
      const err = await orderRes.json().catch(() => ({}));
      return NextResponse.json(
        { error: (err as { message?: string }).message ?? "PayPal order creation failed" },
        { status: 500 },
      );
    }

    const order = await orderRes.json();

    // PayPal returns a "payer-action" link that the buyer must be redirected to
    type PayPalLink = { rel: string; href: string };
    const approvalUrl: string | undefined = (order.links as PayPalLink[] | undefined)?.find(
      (l) => l.rel === "payer-action",
    )?.href;

    if (!approvalUrl) {
      return NextResponse.json(
        { error: "No approval URL returned by PayPal" },
        { status: 500 },
      );
    }

    return NextResponse.json({ paypalOrderId: order.id as string, approvalUrl });
  } catch (err) {
    const message = err instanceof Error ? err.message : "Internal error";
    return NextResponse.json({ error: message }, { status: 500 });
  }
}
