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

  const collection = await db.query.collections.findFirst({
    where: and(eq(collections.id, id), or(eq(collections.isPublic, true), eq(collections.userId, 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 requireSession();
  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 });
}
