import { requireAdminApi } from "@/lib/admin-api";
import { prisma } from "@/lib/prisma";
import { NextResponse } from "next/server";

export async function GET() {
  const deny = await requireAdminApi();
  if (deny) return deny;

  const row = await prisma.siteContent.findUnique({ where: { id: "main" } });
  return NextResponse.json(row);
}

export async function PATCH(req: Request) {
  const deny = await requireAdminApi();
  if (deny) return deny;

  try {
    const body = await req.json();
    const data: Record<string, string> = {};

    const keys = [
      "aboutEn",
      "aboutAr",
      "aboutRu",
      "aboutIt",
      "addressEn",
      "addressAr",
      "addressRu",
      "addressIt",
      "mapEmbedUrl",
      "socialInstagram",
      "socialFacebook",
      "socialTiktok",
      "socialWhatsapp",
      "socialEmail",
    ] as const;

    for (const k of keys) {
      if (typeof body[k] === "string") data[k] = body[k];
    }

    const row = await prisma.siteContent.upsert({
      where: { id: "main" },
      create: { id: "main", ...data },
      update: data,
    });

    return NextResponse.json(row);
  } catch {
    return NextResponse.json({ error: "Bad request" }, { status: 400 });
  }
}
