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

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

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

  // Allow forking public collections or own collections
  const source = await db.query.collections.findFirst({
    where: and(
      eq(collections.id, id),
      or(eq(collections.isPublic, true), eq(collections.userId, 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,
    isPublic: false,
    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 });
}
