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

import { ROUTES } from "@/shared/constants/client-routes";

function extractTrackingCookiesFromUrl(url: URL): Record<string, string> {
  const trackingCookieKeys = [
    "_fbc",
    "_fbp",
    "_ym_uid",
    "_ym_d",
    "_ym_isad",
    "_ym_visorc",
    "yandexuid",
    "ymex",
  ];

  const cookies: Record<string, string> = {};

  for (const [key, value] of url.searchParams.entries()) {
    if (
      trackingCookieKeys.includes(key) ||
      key.startsWith("_ga") ||
      key.startsWith("_gid")
    ) {
      cookies[key] = value;
    }
  }

  return cookies;
}

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

  const redirectUrl = new URL(
    `${nextUrl || ROUTES.payment()}`,
    process.env.NEXT_PUBLIC_APP_URL || ""
  );

  if (productId) redirectUrl.searchParams.set("productId", productId);
  if (placementId) redirectUrl.searchParams.set("placementId", placementId);
  if (paywallId) redirectUrl.searchParams.set("paywallId", paywallId);
  if (fbPixels) redirectUrl.searchParams.set("fb_pixels", fbPixels);
  if (productPrice) redirectUrl.searchParams.set("price", productPrice);
  if (currency) redirectUrl.searchParams.set("currency", currency);

  const trackingCookies = extractTrackingCookiesFromUrl(req.nextUrl);

  const cookies: string[] = [];

  cookies.push(
    `accessToken=${encodeURIComponent(token || "")}; HttpOnly; Secure; Path=/; SameSite=Lax; Max-Age=${60 * 60 * 24 * 365}`
  );

  // Ставим куку через заголовок Set-Cookie, тк в HTML-ответе NextResponse.cookies не работает
  Object.entries(trackingCookies).forEach(([key, value]) => {
    cookies.push(
      `${key}=${encodeURIComponent(value)}; HttpOnly=false; Secure=false; Path=/; SameSite=Lax; Max-Age=${60 * 60 * 24 * 365}`
    );
  });

  const html = `
      <!DOCTYPE html>
      <html>
        <head>
          <meta http-equiv="refresh" content="0; url=${redirectUrl}" />
          <script>
            window.location.replace(${JSON.stringify(redirectUrl.toString())});
          </script>
        </head>
        <body>
          <p>Redirecting...</p>
        </body>
      </html>
    `;

  return new NextResponse(html, {
    status: 200,
    headers: {
      "content-type": "text/html; charset=utf-8",
      "set-cookie": cookies.join(", "),
    },
  });
}
