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

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

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

  const plan = await db.query.mealPlans.findFirst({
    where: and(eq(mealPlans.userId, session!.user.id), eq(mealPlans.weekStart, weekStart)),
  });
  if (!plan) return NextResponse.json({ error: "Not found" }, { status: 404 });

  await db.delete(mealPlanEntries).where(
    and(eq(mealPlanEntries.id, entryId), eq(mealPlanEntries.mealPlanId, plan.id))
  );

  return new NextResponse(null, { status: 204 });
}
