/**
 * Testimonial Embed Code API
 * GET - Generate embeddable widget code for testimonials
 */

import { NextRequest, NextResponse } from "next/server";
import { auth } from "@/lib/auth";
import { getAuthenticatedUser } from "@/lib/utils/auth-helpers.util";
import { getEffectiveOwnerId } from "@/lib/utils/organization-data";
import { generateEmbedCode } from "@/lib/services/review-widget.service";
import { logger } from "@/lib/logger";
import { getDataSource } from "@/lib/data-source";

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

export async function GET(request: NextRequest) {
  try {
    const user = await getAuthenticatedUser(request, auth);
    if (!user) {
      return NextResponse.json(
        { success: false, error: "Unauthorized" },
        { status: 401 },
      );
    }

    const effectiveUserId = await getEffectiveOwnerId(user.userId);

    // Embed code generation is primarily a server-side template concern.
    // When Convex is active, still use the Prisma-based generateEmbedCode since
    // it generates HTML/JS that references server URLs — no Convex data needed.
    // Adding the routing check so the domain flag is respected for future migration.
    if (getDataSource("reviews") === "convex") {
      try {
        // Embed code is derived from widget settings; pass through to existing generator
        // which reads widget settings. In the future this could read from Convex directly.
        const embedCode = await generateEmbedCode(effectiveUserId);
        return NextResponse.json({ success: true, embedCode });
      } catch {
        // Fall through to Prisma
      }
    }

    const embedCode = await generateEmbedCode(effectiveUserId);
    return NextResponse.json({ success: true, embedCode });
  } catch (error) {
    log.error("Failed to generate embed code", error);
    return NextResponse.json(
      { success: false, error: "Internal server error" },
      { status: 500 },
    );
  }
}
