/**
 * Testimonial Reorder API
 * PUT - Reorder featured reviews display order
 */

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 { reorderFeaturedReviews } from "@/lib/services/review-widget.service";
import { ReorderFeaturedSchema } from "@/lib/validators/reviews.validator";
import { logger } from "@/lib/logger";
import { getDataSource } from "@/lib/data-source";

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

export async function PUT(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);
    const body = await request.json();
    const parsed = ReorderFeaturedSchema.safeParse(body);

    if (!parsed.success) {
      return NextResponse.json(
        { success: false, error: parsed.error.flatten() },
        { status: 400 },
      );
    }

    if (getDataSource("reviews") === "convex") {
      try {
        const { convexMutation } = await import("@/lib/convex-client");
        await convexMutation("reviews/mutations:reorderFeaturedReviews", {
          userId: effectiveUserId,
          orderedIds: parsed.data.orderedIds as string[],
        });
        return NextResponse.json({ success: true });
      } catch {
        // Fall through to Prisma
      }
    }

    await reorderFeaturedReviews(effectiveUserId, parsed.data.orderedIds);
    return NextResponse.json({ success: true });
  } catch (error) {
    log.error("Failed to reorder featured reviews", error);
    return NextResponse.json(
      { success: false, error: "Internal server error" },
      { status: 500 },
    );
  }
}
