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

/**
 * POST /api/quotations/portal/[token]/decline
 * Public - no auth required. Decline a quotation via portal token.
 */
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 },
      );
    }

    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 },
      );
    }

    // Allow decline for SENT, VIEWED, or already DECLINED (idempotent)
    if (quotation.status === "DECLINED") {
      return NextResponse.json({ success: true });
    }

    if (quotation.status !== "SENT" && quotation.status !== "VIEWED") {
      return NextResponse.json(
        {
          success: false,
          error: `Cannot decline quotation with status ${quotation.status}`,
        },
        { status: 400 },
      );
    }

    await convexMutation("quotations/mutations:rejectQuotation", {
      id: quotation._id,
    });

    return NextResponse.json({ success: true });
  } catch (error) {
    console.error("[Portal Decline] Error:", error);
    return NextResponse.json(
      { success: false, error: "Internal server error" },
      { status: 500 },
    );
  }
}
