import { NextRequest, NextResponse } from "next/server";
import { randomUUID } from "crypto";
import { z } from "zod";
import { requireAdmin } from "@/lib/api-auth";
import { db, recipes, auditLogs, eq } from "@epicure/db";

const PatchSchema = z.object({
  action: z.literal("unpublish"),
});

/** Admin/moderator takedown action — flips a public recipe to private.
 * Deliberately narrow (just this one transition) rather than exposing full
 * visibility management here, since that's the recipe owner's call. */
export async function PATCH(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
  const { session, response } = await requireAdmin({ allowModerator: true });
  if (response) return response;

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

  const [updated] = await db
    .update(recipes)
    .set({ visibility: "private" })
    .where(eq(recipes.id, id))
    .returning({ id: recipes.id });

  if (!updated) return NextResponse.json({ error: "Not found" }, { status: 404 });

  await db.insert(auditLogs).values({
    id: randomUUID(),
    userId: session!.user.id,
    action: "admin.recipe.unpublish",
    targetType: "recipe",
    targetId: id,
    metadata: null,
    createdAt: new Date(),
  });

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