"use server";

import { revalidatePath } from "next/cache";
import { z } from "zod";
import { prisma } from "@/lib/db";
import { isAdmin } from "@/lib/admin-auth";
import { sanitizeForDisplay } from "@/lib/sanitize";

function ensureAdmin() {
  if (!isAdmin()) throw new Error("Unauthorized");
}

const ApproveSchema = z.object({ id: z.string().min(1).max(50) });
const RejectSchema = z.object({ id: z.string().min(1).max(50) });
const EditSchema = 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 approveDonation(formData: FormData) {
  ensureAdmin();
  const { id } = ApproveSchema.parse({ id: formData.get("id") });

  const donation = await prisma.donation.findUnique({ where: { id } });
  if (!donation) throw new Error("Not found");
  if (donation.status === "APPROVED") return;

  await prisma.$transaction(async (tx) => {
    await tx.donation.update({
      where: { id },
      data: { status: "APPROVED", approvedAt: new Date() },
    });
    const settings = 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 settings;
  });

  revalidatePath("/admin/moderate");
  revalidatePath("/donate");
  revalidatePath("/donate/donors");
}

export async function rejectDonation(formData: FormData) {
  ensureAdmin();
  const { id } = RejectSchema.parse({ id: formData.get("id") });
  await prisma.donation.update({
    where: { id },
    data: { status: "REJECTED" },
  });
  revalidatePath("/admin/moderate");
}

export async function editDonation(formData: FormData) {
  ensureAdmin();
  const parsed = EditSchema.parse({
    id: formData.get("id"),
    message: formData.get("message"),
    donorName: (formData.get("donorName") as string | null) || null,
    websiteUrl: (formData.get("websiteUrl") as string | null) || null,
  });

  await prisma.donation.update({
    where: { id: parsed.id },
    data: {
      message: sanitizeForDisplay(parsed.message),
      donorName: parsed.donorName,
      websiteUrl: parsed.websiteUrl,
    },
  });

  revalidatePath("/admin/moderate");
  revalidatePath("/donate");
  revalidatePath("/donate/donors");
}
