import type { Prisma } from "@prisma/client";
import prisma from "@/server/db/prisma";
import { requireAdmin } from "@/server/auth/requireAdmin";
import { HttpError } from "@/server/http/errors";
import { ok } from "@/server/http/response";
import { withErrorHandling } from "@/server/http/withErrorHandling";
import { setCacheHeaders } from "@/server/http/cacheHeaders";

// GET: Fetch hero section data
export const GET = withErrorHandling(async () => {
  const hero = await prisma.hero.findFirst({
    select: {
      id: true,
      title: true,
      description: true,
      background: true,
      buttons: true,
    },
  });
  const response = ok(hero);
  return setCacheHeaders(response, "medium");
});

// POST: Update hero section data
export const POST = withErrorHandling(async (request: Request) => {
  await requireAdmin(request);
  const formData = await request.formData();
  const title = String(formData.get("title") ?? "");
  const description = String(formData.get("description") ?? "");
  const backgroundRaw = formData.get("background");
  const background = backgroundRaw === null ? null : String(backgroundRaw);

  const buttonsRaw = formData.get("buttons");
  let buttons: Prisma.InputJsonValue;
  try {
    buttons = JSON.parse(String(buttonsRaw ?? "[]")) as Prisma.InputJsonValue;
  } catch {
    throw new HttpError("Invalid buttons JSON", { status: 400, code: "INVALID_BUTTONS" });
  }

  if (!title || !description) {
    throw new HttpError("title and description are required", { status: 400, code: "VALIDATION_ERROR" });
  }

  if (title.length > 200) {
    throw new HttpError("title must be at most 200 characters", { status: 400, code: "VALIDATION_ERROR" });
  }
  if (description.length > 2000) {
    throw new HttpError("description must be at most 2000 characters", { status: 400, code: "VALIDATION_ERROR" });
  }

  const updatedHero = await prisma.hero.upsert({
    where: { id: 1 },
    update: { title, description, background, buttons },
    create: { title, description, background, buttons },
    select: {
      id: true,
      title: true,
      description: true,
      background: true,
      buttons: true,
    },
  });

  return ok(updatedHero);
});
