/**
 * Public Thank-You Page Data API (NO AUTH)
 * GET /api/public/review/[token]/thank-you
 *
 * Returns widget branding for the thank-you page after a review is submitted.
 * Looks up by token regardless of status (review is already COMPLETED at this point).
 */

import { NextRequest, NextResponse } from "next/server";
import { logger } from "@/lib/logger";

export const dynamic = "force-dynamic";

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

export async function GET(
  _request: NextRequest,
  { params }: { params: Promise<{ token: string }> },
) {
  try {
    const { token } = await params;
    const { convexQuery } = await import("@/lib/convex-client");

    // Look up the request by token — no status filter since it's already COMPLETED
    const reviewRequest = (await convexQuery(
      "reviews/queries:getReviewRequestByToken",
      { token },
    )) as { userId: string } | null;

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

    // Get widget settings from Convex
    const ws = ((await convexQuery("reviews/queries:getWidgetSettings", {
      userId: reviewRequest.userId,
    }).catch(() => null)) ?? {}) as Record<string, unknown>;

    return NextResponse.json({
      success: true,
      businessName: (ws.businessName as string) ?? "Mawidi",
      logoUrl: (ws.logoUrl as string | null) ?? null,
      primaryColor: (ws.primaryColor as string) ?? "#10b981",
      bgColor:
        (ws.backgroundColor as string) ?? (ws.bgColor as string) ?? "#ffffff",
      thankYouMessage: (ws.thankYouMessage as string | null) ?? null,
      showPoweredBy: (ws.showPoweredBy as boolean) ?? true,
    });
  } catch (error) {
    log.error("thank-you API error", error);
    return NextResponse.json(
      { success: false, error: "Internal server error" },
      { status: 500 },
    );
  }
}
