import { NextResponse } from "next/server";

const baseUrl = process.env.APP_BASE_URL!;

const PAYSAFE_BASE_URL =
  process.env.PAYSAFE_ENV === "live"
    ? "https://api.paysafe.com"
    : "https://api.test.paysafe.com";

export async function POST(req: Request) {
  const body = await req.json();
  console.log("ENV", {
    env: process.env.PAYSAFE_ENV,
    key: process.env.PAYSAFE_API_KEY,
    passLen: process.env.PAYSAFE_API_PASSWORD?.length,
    acc: process.env.PAYSAFE_ACCOUNT_NUMBER,
  });

  const auth = Buffer.from(
    `${process.env.PAYSAFE_API_KEY}:${process.env.PAYSAFE_API_PASSWORD}`
  ).toString("base64");

  const res = await fetch(`${PAYSAFE_BASE_URL}/paymenthub/v1/paymenthandles`, {
    method: "POST",
    headers: {
      Authorization: `Basic ${auth}`,
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      merchantRefNum: `order_${Date.now()}`,
      transactionType: "PAYMENT",
      paymentType: "CARD",
      amount: body.amount, // cents (10.00)
      currencyCode: body.currencyCode || "USD",
      accountId: String(process.env.PAYSAFE_ACCOUNT_NUMBER).trim(),
      card: body.card, // cardNum, cvv, cardExpiry
      billingDetails: body.billingDetails,
      //   card: {
      //     cardNum: "4111111111111111",
      //     cvv: "123",
      //     cardExpiry: {
      //       month: 12,
      //       year: 2027,
      //     },
      //   },
      //   billingDetails: {
      //     country: "US",
      //     zip: "10001",
      //   },

      returnLinks: [
        { rel: "default", href: `${baseUrl}/wallet`, method: "GET" },
        { rel: "on_completed", href: `${baseUrl}/success`, method: "GET" },
        { rel: "on_failed", href: `${baseUrl}/failed`, method: "GET" },
      ],
    }),
  });

  const data = await res.json();
  console.log("data of paysafe", data);
  return NextResponse.json(data, { status: res.status });
}
