import { NextRequest, NextResponse } from "next/server";
import { z } from "zod";
import { prisma } from "@/lib/db";
import { isAdmin } from "@/lib/admin-auth";
import { sanitizeForDisplay, safeUrl } from "@/lib/sanitize";

export const runtime = "nodejs";

const Body = z.object({
  id: z.string().min(1).max(50),
  message: z.string().min(1).max(60),
  donorName: z.string().max(120).nullable().optional(),
  websiteUrl: z.string().max(500).nullable().optional(),
});

export async function POST(req: NextRequest) {
  if (!isAdmin()) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  let body;
  try {
    body = Body.parse(await req.json());
  } catch {
    return NextResponse.json({ error: "Invalid request" }, { status: 400 });
  }

  await prisma.donation.update({
    where: { id: body.id },
    data: {
      message: sanitizeForDisplay(body.message),
      donorName: body.donorName ?? null,
      websiteUrl: body.websiteUrl ? safeUrl(body.websiteUrl) : null,
    },
  });

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