import { z } from "zod";
import prisma from "@/server/db/prisma";
import { requireAdmin } from "@/server/auth/requireAdmin";
import { parseJson } from "@/server/http/parse";
import { ok } from "@/server/http/response";
import { DeleteByIdSchema } from "@/server/http/schemas";
import { withErrorHandling } from "@/server/http/withErrorHandling";
import { setCacheHeaders } from "@/server/http/cacheHeaders";

// GET: Fetch all about section cards
export const GET = withErrorHandling(async () => {
  const aboutCards = await prisma.about.findMany({
    select: {
      id: true,
      title: true,
      description: true,
      icon: true,
    },
  });
  const response = ok(aboutCards);
  return setCacheHeaders(response, "medium");
});

// POST: Add or update about section cards (no image field)
const AboutUpsertSchema = z.object({
  id: z.coerce.number().int().optional(),
  title: z.string().min(1).max(200),
  description: z.string().min(1).max(2000),
  icon: z.string().min(1).max(100),
});

export const POST = withErrorHandling(async (request: Request) => {
  await requireAdmin(request);
  const contentType = request.headers.get("content-type") || "";

  const parsed = contentType.includes("multipart/form-data")
    ? await (async () => {
        const formData = await request.formData();
        return AboutUpsertSchema.parse({
          id: formData.get("id") ?? undefined,
          title: formData.get("title"),
          description: formData.get("description"),
          icon: formData.get("icon"),
        });
      })()
    : await parseJson(request, AboutUpsertSchema);

  if (parsed.id) {
    const updatedCard = await prisma.about.update({
      where: { id: parsed.id },
      data: { title: parsed.title, description: parsed.description, icon: parsed.icon },
      select: {
        id: true,
        title: true,
        description: true,
        icon: true,
      },
    });
    return ok(updatedCard);
  }

  const newCard = await prisma.about.create({
    data: { title: parsed.title, description: parsed.description, icon: parsed.icon },
    select: {
      id: true,
      title: true,
      description: true,
      icon: true,
    },
  });
  return ok(newCard);
});

// DELETE: Remove an about section card
export const DELETE = withErrorHandling(async (request: Request) => {
  await requireAdmin(request);
  const { id } = await parseJson(request, DeleteByIdSchema);
  const deletedCard = await prisma.about.delete({
    where: { id },
    select: {
      id: true,
      title: true,
      description: true,
      icon: true,
    },
  });
  return ok({ message: "Card deleted successfully", card: deletedCard });
});
