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

function parseBody(body: unknown) {
  return typeof body === "object" && body !== null ? (body as Record<string, unknown>) : {};
}

function parseWebhookPaymentId(url: URL, body: Record<string, unknown>) {
  const fromQuery = url.searchParams.get("data.id")?.trim() || url.searchParams.get("id")?.trim() || "";

  if (fromQuery) {
    return fromQuery;
  }

  const data = typeof body.data === "object" && body.data !== null ? (body.data as Record<string, unknown>) : null;
  return typeof data?.id === "string" || typeof data?.id === "number" ? String(data.id) : "";
}

async function processWebhook(request: Request, body: Record<string, unknown>) {
  if (!hasMercadoPagoConfig()) {
    return NextResponse.json({ ok: true });
  }

  const requestUrl = new URL(request.url);
  const eventType = (typeof body.type === "string" ? body.type : requestUrl.searchParams.get("type") || requestUrl.searchParams.get("topic") || "").toLowerCase();
  const paymentId = parseWebhookPaymentId(requestUrl, body);

  if (eventType && eventType !== "payment") {
    return NextResponse.json({ ok: true });
  }

  if (!paymentId) {
    return NextResponse.json({ ok: true });
  }

  try {
    const payment = await fetchMercadoPaymentById(paymentId);

    if (!payment.external_reference) {
      return NextResponse.json({ ok: true });
    }

    await syncPurchaseFromPayment(prisma, {
      externalReference: payment.external_reference,
      paymentId,
      paymentStatus: payment.status,
      mercadoOrderId: payment.order?.id || null,
      rawPayload: payment,
    });

    return NextResponse.json({ ok: true });
  } catch {
    return NextResponse.json({ ok: true });
  }
}

export async function POST(request: Request) {
  const body = parseBody(await request.json().catch(() => ({})));
  return processWebhook(request, body);
}

export async function GET(request: Request) {
  return processWebhook(request, {});
}
