import { NextRequest, NextResponse } from "next/server";
import { db, recipes, favorites, eq, and } from "@epicure/db";
import { requireSessionOrApiKey } from "@/lib/api-auth";

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 recipe = await db.query.recipes.findFirst({ where: eq(recipes.id, id) });
  if (!recipe || recipe.visibility === "private" && recipe.authorId !== session!.user.id) {
    return NextResponse.json({ error: "Not found" }, { status: 404 });
  }

  await db.insert(favorites).values({ userId: session!.user.id, recipeId: 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(favorites).where(and(eq(favorites.userId, session!.user.id), eq(favorites.recipeId, id)));
  return NextResponse.json({ favorited: false });
}
