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 navbar data
export const GET = withErrorHandling(async () => {
  const navbar = await prisma.navbar.findFirst();
  return ok(navbar);
});

// POST: Update navbar data
const NavbarLinkSchema = z.object({
  id: z.string().min(1),
  label: z.string().min(1),
  url: z.string(),
  newTab: z.boolean().default(false),
  order: z.number().int().nonnegative(),
  isScrollLink: z.boolean().default(false),
});

const NavbarUpsertSchema = z.object({
  branding: z.string().min(1),
  links: z.array(NavbarLinkSchema),
});

async function upsertNavbar(request: Request) {
  const { branding, links } = await parseJson(request, NavbarUpsertSchema);

  const updatedNavbar = await prisma.navbar.upsert({
    where: { id: 1 },
    update: { branding, links },
    create: { branding, links },
  });

  return ok(updatedNavbar);
}

export const POST = withErrorHandling(upsertNavbar);

// PUT: Alias for POST (both perform upsert)
export const PUT = withErrorHandling(upsertNavbar);
