/**
 * Public Testimonials API (NO AUTH)
 * GET - Return widget settings AND featured testimonials for embedding
 * Response shape: { settings: {...}, testimonials: [...] }
 */

import { NextRequest, NextResponse } from "next/server";
import {
  listFeaturedReviews,
  getWidgetSettings,
} from "@/lib/services/review-widget.service";
import { convexQuery } from "@/lib/convex-client";
import { logger } from "@/lib/logger";
import { corsHeaders } from "@/lib/cors";

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

export async function GET(
  _request: NextRequest,
  { params }: { params: Promise<{ userId: string }> },
) {
  try {
    const { userId } = await params;

    const [settings, testimonials] = await Promise.all([
      getWidgetSettings(userId),
      listFeaturedReviews(userId),
    ]);

    // Always use the canonical company name from Convex user record
    let resolvedSettings: Record<string, unknown> | null = settings as Record<string, unknown> | null;
    try {
      const companyName = await convexQuery<string | null>(
        "auth/queries:getCompanyNameByAppUserId",
        { appUserId: userId },
      );
      if (companyName && resolvedSettings) {
        resolvedSettings = { ...resolvedSettings, businessName: companyName };
      }
    } catch {
      // Non-critical
    }

    // Return CORS-friendly response for embedding
    return NextResponse.json(
      { settings: resolvedSettings, testimonials },
      {
        headers: {
          ...corsHeaders("GET"),
          "Cache-Control": "public, max-age=300, s-maxage=600",
        },
      },
    );
  } catch (error) {
    log.error("Failed to get public testimonials", error);
    return NextResponse.json(
      { success: false, error: "Internal server error" },
      { status: 500 },
    );
  }
}
