import { NextRequest, NextResponse } from "next/server";
import { convexQuery } from "@/lib/convex-client";
import { createQuotationCheckoutSession } from "@/lib/stripe/quotation-checkout";
import { validateCSRFToken } from "@/lib/csrf";

/**
 * POST /api/quotations/portal/[token]/pay
 * Public - no auth required. Creates a Stripe checkout session for quotation payment.
 */
export async function POST(
  req: NextRequest,
  { params }: { params: Promise<{ token: string }> },
) {
  if (process.env.NODE_ENV !== "development") {
    const csrfValid = validateCSRFToken(req);
    if (!csrfValid) {
      return NextResponse.json({ error: "Invalid CSRF token" }, { status: 403 });
    }
  }

  try {
    const { token } = await params;

    if (!token || token.length < 5) {
      return NextResponse.json(
        { success: false, error: "Invalid token" },
        { status: 400 },
      );
    }

    // Fetch quotation from Convex
    const quotation = await convexQuery<Record<string, unknown>>(
      "quotations/queries:getQuotationByPortalToken",
      { portalToken: token },
    );

    if (!quotation) {
      return NextResponse.json(
        { success: false, error: "Quotation not found" },
        { status: 404 },
      );
    }

    const remaining =
      (quotation.total as number) +
      ((quotation.penaltyAmount as number) || 0) -
      ((quotation.amountPaid as number) || 0);

    if (remaining <= 0) {
      return NextResponse.json(
        { success: false, error: "Quotation is already fully paid" },
        { status: 400 },
      );
    }

    // Get Stripe key — platform key
    const stripeSecretKey = process.env.STRIPE_SECRET_KEY;
    if (!stripeSecretKey) {
      return NextResponse.json(
        { success: false, error: "Payment processing not configured" },
        { status: 503 },
      );
    }

    const appUrl =
      process.env.NEXT_PUBLIC_APP_URL ||
      process.env.NEXTAUTH_URL ||
      "http://localhost:9001";

    const quotationId = quotation._id as string;
    const quotationNumber = (quotation.quotationNumber as string) || "";

    const result = await createQuotationCheckoutSession({
      stripeSecretKey,
      quotationId,
      quotationNumber,
      title: (quotation.title as string) || "Payment",
      currency: (quotation.currency as string) || "QAR",
      amount: remaining,
      portalToken: token,
      appUrl,
    });

    return NextResponse.json({
      success: true,
      checkoutUrl: result.checkoutUrl,
    });
  } catch (error) {
    const msg = error instanceof Error ? error.message : String(error);
    console.error("[Portal Pay] Error:", msg);

    // Surface Stripe currency errors clearly
    if (msg.includes("Invalid currency")) {
      const currency = (
        (msg.match(/Invalid currency: (\w+)/) || [])[1] || ""
      ).toUpperCase();
      return NextResponse.json(
        {
          success: false,
          error: `Online payment is not available for ${currency} currency. Please contact the business for alternative payment methods.`,
        },
        { status: 400 },
      );
    }

    return NextResponse.json(
      {
        success: false,
        error: "Failed to create payment session. Please try again.",
      },
      { status: 500 },
    );
  }
}
