import { z } from "zod";
import prisma from "@/server/db/prisma";
import { parseJson } from "@/server/http/parse";
import { ok } from "@/server/http/response";
import { withErrorHandling } from "@/server/http/withErrorHandling";

// GET: Fetch services CTA settings
export const GET = withErrorHandling(async () => {
  let ctaSettings = await prisma.servicescta.findFirst();
  if (!ctaSettings) {
    ctaSettings = await prisma.servicescta.create({
      data: { buttonText: "Get Started", buttonLink: "/contact" },
    });
  }
  return ok(ctaSettings);
});

// POST: Update services CTA settings
const ServicesCtaSchema = z.object({
  buttonText: z.string().min(1),
  buttonLink: z.string().min(1),
});

export const POST = withErrorHandling(async (request: Request) => {
  const body = await parseJson(request, ServicesCtaSchema);
  const buttonText = body.buttonText.trim();
  const buttonLink = body.buttonLink.trim();

  const ctaSettings = await prisma.servicescta.upsert({
    where: { id: 1 },
    update: { buttonText, buttonLink },
    create: { buttonText, buttonLink },
  });

  return ok(ctaSettings);
});
