import { b2bFetch, getB2binpayToken } from "@/app/lib/b2binpay";
import { NextResponse } from "next/server";
// import { b2bFetch, getB2binpayToken } from "@/lib/b2binpay";

export async function POST(req: Request) {
  const { walletId, trackingId } = await req.json();

  const token = await getB2binpayToken();

  // IMPORTANT: callback_url must be publicly reachable (use ngrok in dev)
  const callbackUrl = `${process.env.NEXT_PUBLIC_BASE_URL}/api/b2binpay/webhook`;

  const payload = {
    data: {
      type: "deposit",
      attributes: {
        label: "Order deposit",
        tracking_id: trackingId,
        confirmations_needed: 2,
        callback_url: callbackUrl,
        // optional UI fields shown in docs:
        payment_page_redirect_url: `${process.env.NEXT_PUBLIC_BASE_URL}/payment/return`,
        payment_page_button_text: "Back to site",
      },
      relationships: {
        wallet: { data: { type: "wallet", id: String(walletId) } },
      },
    },
  };

  const json = await b2bFetch("/deposit/", token, {
    method: "POST",
    body: JSON.stringify(payload),
  });

  // In the deposit response example, you typically get a payment_page URL to redirect the user.
  // (Field name: attributes.payment_page)
  const paymentPage = json?.data?.attributes?.payment_page;

  return NextResponse.json({ deposit: json.data, paymentPage });
}
