import { NextRequest, NextResponse } from "next/server";
import { db, collections, collectionRecipes, eq, and } from "@epicure/db";
import { requireSessionOrApiKey } from "@/lib/api-auth";
import { collectionVisibleToViewer } from "@/lib/visibility";

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

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

  // Allow forking any collection visible to this viewer (own, or public/
  // unlisted/followers-if-following) — never a private collection of someone else's.
  const source = await db.query.collections.findFirst({
    where: and(eq(collections.id, id), collectionVisibleToViewer(session!.user.id)),
    with: { recipes: { columns: { recipeId: true } } },
  });

  if (!source) return NextResponse.json({ error: "Not found" }, { status: 404 });

  const newId = crypto.randomUUID();
  await db.insert(collections).values({
    id: newId,
    userId: session!.user.id,
    name: `${source.name} (fork)`,
    description: source.description,
    visibility: "private",
    createdAt: new Date(),
    updatedAt: new Date(),
  });

  if (source.recipes.length > 0) {
    await db.insert(collectionRecipes).values(
      source.recipes.map((r) => ({ collectionId: newId, recipeId: r.recipeId }))
    );
  }

  return NextResponse.json({ id: newId }, { status: 201 });
}
