import { NextRequest, NextResponse } from "next/server";

import { createPaymentCheckout } from "@/entities/payment/api";
import { ROUTES } from "@/shared/constants/client-routes";

export async function GET(req: NextRequest) {
  const productId = req.nextUrl.searchParams.get("productId");
  const placementId = req.nextUrl.searchParams.get("placementId");
  const paywallId = req.nextUrl.searchParams.get("paywallId");
  const fbPixels = req.nextUrl.searchParams.get("fb_pixels");
  const productPrice = req.nextUrl.searchParams.get("price");
  const currency = req.nextUrl.searchParams.get("currency");

  const data = await createPaymentCheckout({
    productId: productId || "",
    placementId: placementId || "",
    paywallId: paywallId || "",
  });

  let redirectUrl: URL = new URL(data?.paymentUrl || "", req.nextUrl.origin);
  if (!redirectUrl) {
    redirectUrl = new URL(`${ROUTES.paymentFailed()}`, origin);
  }
  if (fbPixels) redirectUrl.searchParams.set("fb_pixels", fbPixels);
  if (productPrice) redirectUrl.searchParams.set("price", productPrice);
  if (currency) redirectUrl.searchParams.set("currency", currency);

  return NextResponse.redirect(redirectUrl, { status: 307 });
}
