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

/**
 * POST /api/quotations/portal/[token]/accept
 * Public - no auth required. Accept 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 accept for SENT, VIEWED, or already ACCEPTED (idempotent)
    if (quotation.status === "ACCEPTED") {
      return NextResponse.json({ success: true });
    }

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

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

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