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

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 g = await prisma.galleryImage.update({
    where: { id },
    data: {
      ...(body.title !== undefined && { title: body.title }),
      ...(body.imageUrl != null && { imageUrl: body.imageUrl }),
      ...(body.year != null && { year: Number(body.year) || 0 }),
      ...(body.category !== undefined && { category: body.category }),
      ...(body.sortOrder != null && { sortOrder: Number(body.sortOrder) }),
    },
  });
  return NextResponse.json(g);
}

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