import { randomUUID } from "crypto";
import type { Prisma } from "@prisma/client";
import { NextResponse } from "next/server";
import { getSessionPayload } from "@/lib/auth/session";
import { buildAppUrl, getRequestOrigin } from "@/lib/http/url";
import { createMercadoPreference, hasMercadoPagoConfig } from "@/lib/payments/mercadopago";
import { getModulePlanByUiKey } from "@/lib/payments/plans";
import { prisma } from "@/lib/prisma";

function redirectToDashboard(request: Request, params: Record<string, string>) {
  return NextResponse.redirect(buildAppUrl(request, "/dashboard", params));
}

export async function GET(request: Request) {
  const session = await getSessionPayload();

  if (!session) {
    return NextResponse.redirect(buildAppUrl(request, "/login", { error: "auth_required" }));
  }

  const requestUrl = new URL(request.url);
  const planUiKey = requestUrl.searchParams.get("plan")?.trim() || "";
  const selectedPlan = getModulePlanByUiKey(planUiKey);

  if (!selectedPlan) {
    return redirectToDashboard(request, { mp_error: "invalid_plan" });
  }

  if (!hasMercadoPagoConfig()) {
    return redirectToDashboard(request, { mp_error: "missing_mp_config" });
  }

  const user = await prisma.user.findUnique({
    where: { id: session.userId },
    select: {
      id: true,
      email: true,
    },
  });

  if (!user) {
    return NextResponse.redirect(buildAppUrl(request, "/login", { error: "auth_required" }));
  }

  const externalReference = `${selectedPlan.key}_${user.id}_${Date.now()}_${randomUUID().slice(0, 8)}`;
  const origin = getRequestOrigin(request);
  const returnBase = `${origin}/api/payments/checkout/return`;

  const createdPurchase = await prisma.modulePlanPurchase.create({
    data: {
      userId: user.id,
      planKey: selectedPlan.key,
      amount: selectedPlan.monthlyPrice,
      currency: selectedPlan.currency,
      externalReference,
      requestJson: {
        uiPlan: selectedPlan.uiKey,
        name: selectedPlan.name,
      },
    },
    select: {
      id: true,
    },
  });

  try {
    const preference = await createMercadoPreference({
      externalReference,
      payerEmail: user.email,
      items: [
        {
          id: selectedPlan.uiKey,
          title: `${selectedPlan.name} Modulos ${selectedPlan.moduleStart}-${selectedPlan.moduleEnd}`,
          quantity: 1,
          unit_price: selectedPlan.monthlyPrice,
          currency_id: selectedPlan.currency,
        },
      ],
      successUrl: `${returnBase}?result=success`,
      failureUrl: `${returnBase}?result=failure`,
      pendingUrl: `${returnBase}?result=pending`,
      notificationUrl: `${origin}/api/payments/mercadopago/webhook`,
    });

    const checkoutUrl = preference.initPoint || preference.sandboxInitPoint;

    await prisma.modulePlanPurchase.update({
      where: { id: createdPurchase.id },
      data: {
        mercadoPreferenceId: preference.id || null,
        checkoutUrl: checkoutUrl || null,
        responseJson: preference.rawPayload as Prisma.InputJsonValue,
      },
    });

    if (!checkoutUrl) {
      return redirectToDashboard(request, { mp_error: "missing_checkout_url" });
    }

    return NextResponse.redirect(checkoutUrl);
  } catch {
    return redirectToDashboard(request, { mp_error: "checkout_create_failed" });
  }
}
