import { NextRequest, NextResponse } from "next/server";
import { db, recipes, recipeSnapshots } from "@epicure/db";
import { eq, and, desc } from "@epicure/db";
import { requireSessionOrApiKey } from "@/lib/api-auth";
import { requireFeatureEnabledResponse } from "@/lib/feature-flags";

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

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

  const featureDenied = await requireFeatureEnabledResponse(session!.user.id, "version_history");
  if (featureDenied) return featureDenied;

  const { id } = await params;

  // Verify ownership
  const recipe = await db.query.recipes.findFirst({
    where: and(eq(recipes.id, id), eq(recipes.authorId, session!.user.id)),
  });
  if (!recipe) return NextResponse.json({ error: "Not found" }, { status: 404 });

  const versions = await db
    .select({
      id: recipeSnapshots.id,
      version: recipeSnapshots.version,
      title: recipeSnapshots.title,
      createdAt: recipeSnapshots.createdAt,
    })
    .from(recipeSnapshots)
    .where(and(eq(recipeSnapshots.recipeId, id), eq(recipeSnapshots.authorId, session!.user.id)))
    .orderBy(desc(recipeSnapshots.version))
    .limit(20);

  return NextResponse.json(versions);
}
