import { NextRequest, NextResponse } from "next/server";
import { db, recipes, ratings, eq, and, or, inArray, desc } from "@epicure/db";
import { requireSessionOrApiKey } from "@/lib/api-auth";

type Params = { params: Promise<{ id: string }> };

export async function GET(req: NextRequest, { params }: Params) {
  const { session, response } = await requireSessionOrApiKey(req);
  if (response) return response;
  const { id } = await params;

  const recipe = await db.query.recipes.findFirst({
    where: and(
      eq(recipes.id, id),
      or(eq(recipes.authorId, session!.user.id), inArray(recipes.visibility, ["public", "unlisted"]))
    ),
    columns: { id: true },
  });
  if (!recipe) return NextResponse.json({ error: "Not found" }, { status: 404 });

  const rows = await db.query.ratings.findMany({
    where: eq(ratings.recipeId, id),
    orderBy: desc(ratings.createdAt),
    limit: 50,
    with: {
      user: { columns: { id: true, name: true, username: true, avatarUrl: true } },
    },
  });

  const reviews = rows
    .filter((r) => r.reviewText || r.photoKey)
    .map((r) => ({
      id: r.id,
      score: r.score,
      reviewText: r.reviewText,
      photoKey: r.photoKey,
      createdAt: r.createdAt,
      user: r.user,
    }));

  return NextResponse.json({ data: reviews });
}
