import { NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";
import { requireAdmin, unauthorized } from "@/lib/admin-api";
import { DocumentCategory, DocumentSection, DocumentSubCategory } from "@prisma/client";

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

export async function PATCH(req: Request, ctx: Ctx) {
  const admin = await requireAdmin();
  if (!admin) return unauthorized();
  const { id } = await ctx.params;
  const body = await req.json();
  const doc = await prisma.document.update({
    where: { id },
    data: {
      ...(body.title != null && { title: body.title }),
      ...(body.description !== undefined && { description: body.description }),
      ...(body.fileUrl != null && { fileUrl: body.fileUrl }),
      ...(body.fileName != null && { fileName: body.fileName }),
      ...(body.mimeType !== undefined && { mimeType: body.mimeType }),
      ...(body.category && { category: body.category as DocumentCategory }),
      ...(body.section && { section: body.section as DocumentSection }),
      ...(body.subCategory && {
        subCategory: body.subCategory as DocumentSubCategory,
      }),
    },
  });
  return NextResponse.json(doc);
}

export async function DELETE(_req: Request, ctx: Ctx) {
  const admin = await requireAdmin();
  if (!admin) return unauthorized();
  await prisma.document.delete({ where: { id: (await ctx.params).id } });
  return NextResponse.json({ ok: true });
}
