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

export const runtime = "nodejs";

const Body = z.object({ id: z.string().min(1).max(50) });

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 });
  }
  const donation = await prisma.donation.findUnique({ where: { id: body.id } });
  if (!donation) return NextResponse.json({ error: "Not found" }, { status: 404 });
  if (donation.status === "APPROVED") return NextResponse.json({ ok: true });

  await prisma.$transaction(async (tx) => {
    await tx.donation.update({
      where: { id: body.id },
      data: { status: "APPROVED", approvedAt: new Date() },
    });
    await tx.settings.upsert({
      where: { id: 1 },
      create: { id: 1, totalRaisedCents: donation.amountCents },
      update: { totalRaisedCents: { increment: donation.amountCents } },
    });
    if (donation.tierId === "naming-rights") {
      await tx.settings.update({
        where: { id: 1 },
        data: {
          namingRightsClaimed: true,
          namingRightsBy: donation.donorName ?? "Anonymous",
        },
      });
    }
  });

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