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

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

const PatchSchema = z.object({
  servings: z.number().int().min(1).max(1000).nullable().optional(),
  notes: z.string().max(2000).nullable().optional(),
  cookedAt: z.string().optional(),
});

// Plain (non-batch) cook log entries only — see the sibling GET's comment.
// Editing/deleting never touches pantry quantities: the deduction (if any)
// already happened at creation time and isn't reversible from here.
export async function PATCH(req: NextRequest, { params }: Params) {
  const { session, response } = await requireSessionOrApiKey(req);
  if (response) return response;
  const { id, logId } = await params;

  const log = await db.query.cookingHistory.findFirst({
    where: and(eq(cookingHistory.id, logId), eq(cookingHistory.recipeId, id), eq(cookingHistory.userId, session!.user.id), isNull(cookingHistory.batchDishId)),
  });
  if (!log) return NextResponse.json({ error: "Not found" }, { status: 404 });

  const parsed = PatchSchema.safeParse(await req.json().catch(() => null));
  if (!parsed.success) return NextResponse.json({ error: "Validation error" }, { status: 400 });

  const data = parsed.data;
  const cookedAt = data.cookedAt ? new Date(data.cookedAt) : undefined;

  await db.update(cookingHistory).set({
    ...(data.servings !== undefined && { servings: data.servings ?? undefined }),
    ...(data.notes !== undefined && { notes: data.notes ?? undefined }),
    ...(cookedAt && !isNaN(cookedAt.getTime()) && { cookedAt }),
  }).where(eq(cookingHistory.id, logId));

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

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

  await db.delete(cookingHistory).where(
    and(eq(cookingHistory.id, logId), eq(cookingHistory.recipeId, id), eq(cookingHistory.userId, session!.user.id), isNull(cookingHistory.batchDishId))
  );

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