import { NextResponse } from "next/server";
import { ContentPageType } from "@prisma/client";
import { requireAdminApiUser } from "@/lib/auth/admin";
import { prisma } from "@/lib/prisma";
import { buildAppUrl } from "@/lib/http/url";

function redirectTo(request: Request, status: string) {
  return NextResponse.redirect(buildAppUrl(request, "/admin", { status }));
}

function asString(formData: FormData, key: string) {
  const value = formData.get(key);
  return typeof value === "string" ? value.trim() : "";
}

export async function POST(request: Request) {
  const adminUser = await requireAdminApiUser();

  if (!adminUser) {
    return redirectTo(request, "admin_error");
  }

  const formData = await request.formData();

  const id = asString(formData, "id");
  const typeValue = asString(formData, "type");
  const slug = asString(formData, "slug");
  const title = asString(formData, "title");
  const content = asString(formData, "content");
  const sortOrder = Number.parseInt(asString(formData, "sortOrder") || "0", 10);
  const isPublished = formData.get("isPublished") === "on";

  if (!id || !slug || !title || !content || (typeValue !== ContentPageType.FAQ && typeValue !== ContentPageType.MANUAL)) {
    return redirectTo(request, "admin_error");
  }

  try {
    await prisma.contentPage.update({
      where: { id },
      data: {
        type: typeValue as ContentPageType,
        slug,
        title,
        content,
        sortOrder: Number.isNaN(sortOrder) ? 0 : sortOrder,
        isPublished,
      },
    });

    return redirectTo(request, "content_updated");
  } catch {
    return redirectTo(request, "admin_error");
  }
}
