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

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

const BulkDeleteSchema = z.object({
  ids: z.array(z.string()).min(1).max(100),
});

// Clear-a-day / clear-a-week — the meal planner has no per-entry select mode,
// so this is only ever called with either one day's entry ids or the whole
// week's, scoped to the caller's own plan.
export async function DELETE(req: NextRequest, { params }: Params) {
  const { session, response } = await requireSessionOrApiKey(req);
  if (response) return response;
  const { weekStart } = 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 });

  const body = BulkDeleteSchema.safeParse(await req.json());
  if (!body.success) return NextResponse.json({ error: "Validation error" }, { status: 400 });

  await db.delete(mealPlanEntries).where(
    and(inArray(mealPlanEntries.id, body.data.ids), eq(mealPlanEntries.mealPlanId, plan.id))
  );

  return NextResponse.json({ ok: true });
}
