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

const log = logger.scope("QuotationPortalAPI");

/**
 * GET /api/quotations/portal/[token]
 * Public - no auth required. Fetches quotation by portal token.
 * Also marks the quotation as VIEWED on first access.
 */
export async function GET(
  _req: NextRequest,
  { params }: { params: Promise<{ token: string }> },
) {
  try {
    const { token } = await params;

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

    // Fetch quotation with items and payments via 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 },
      );
    }

    // Mark as VIEWED on first access (idempotent)
    if (quotation.status === "SENT") {
      try {
        await convexMutation("quotations/mutations:updateQuotation", {
          id: quotation._id,
          status: "VIEWED",
        });
      } catch {
        // Non-critical
      }
    }

    return NextResponse.json({
      success: true,
      quotation: { ...quotation, id: quotation._id },
    });
  } catch (error) {
    log.error("Portal GET error:", error);
    return NextResponse.json(
      { success: false, error: "Internal server error" },
      { status: 500 },
    );
  }
}
