import { NextRequest, NextResponse } from "next/server";
import { db, collections, collectionFavorites, 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;

  const collection = await db.query.collections.findFirst({
    where: and(eq(collections.id, id), collectionVisibleToViewer(session!.user.id)),
    columns: { id: true },
  });
  if (!collection) return NextResponse.json({ error: "Not found" }, { status: 404 });

  await db.insert(collectionFavorites)
    .values({ userId: session!.user.id, collectionId: id })
    .onConflictDoNothing();
  return NextResponse.json({ favorited: true });
}

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

  await db.delete(collectionFavorites)
    .where(and(eq(collectionFavorites.userId, session!.user.id), eq(collectionFavorites.collectionId, id)));
  return NextResponse.json({ favorited: false });
}
