import { NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";
import { requireAdmin, unauthorized } from "@/lib/admin-api";
import { NewsCategory } 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 news = await prisma.news.update({
    where: { id },
    data: {
      ...(body.title != null && { title: body.title }),
      ...(body.excerpt !== undefined && { excerpt: body.excerpt }),
      ...(body.content != null && { content: body.content }),
      ...(body.imageUrl !== undefined && { imageUrl: body.imageUrl }),
      ...(body.externalUrl !== undefined && { externalUrl: body.externalUrl }),
      ...(body.category && { category: body.category as NewsCategory }),
      ...(body.published !== undefined && { published: Boolean(body.published) }),
    },
  });
  return NextResponse.json(news);
}

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