import { NextResponse } from "next/server";
import { buildAppUrl } from "@/lib/http/url";
import { fetchMercadoPaymentById, hasMercadoPagoConfig } from "@/lib/payments/mercadopago";
import { syncPurchaseFromPayment } from "@/lib/payments/subscriptions";
import { prisma } from "@/lib/prisma";

function pickFirst(url: URL, keys: string[]) {
  for (const key of keys) {
    const value = url.searchParams.get(key)?.trim();

    if (value) {
      return value;
    }
  }

  return "";
}

export async function GET(request: Request) {
  const requestUrl = new URL(request.url);
  const result = requestUrl.searchParams.get("result")?.trim() || "pending";
  const paymentId = pickFirst(requestUrl, ["payment_id", "collection_id"]);
  const externalReference = pickFirst(requestUrl, ["external_reference"]);
  const fallbackStatus = pickFirst(requestUrl, ["status", "collection_status"]) || result;
  const merchantOrderId = pickFirst(requestUrl, ["merchant_order_id"]);

  if (paymentId && externalReference && hasMercadoPagoConfig()) {
    try {
      const payment = await fetchMercadoPaymentById(paymentId);
      const resolvedExternalReference = payment.external_reference || externalReference;

      await syncPurchaseFromPayment(prisma, {
        externalReference: resolvedExternalReference,
        paymentId,
        paymentStatus: payment.status,
        mercadoOrderId: payment.order?.id || merchantOrderId || null,
        rawPayload: payment,
      });
    } catch {
      // Callback reconciliation is best-effort; webhook still updates asynchronously.
    }
  }

  return NextResponse.redirect(
    buildAppUrl(request, "/dashboard", {
      mp_result: result,
      mp_payment_status: fallbackStatus,
    }),
  );
}
