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";

export const GET = withErrorHandling(async () => {
  const seoEntries = await prisma.seometadata.findMany({
    orderBy: { pageType: "asc" },
  });
  return ok(seoEntries);
});

const PageTypeSchema = z.enum(["PROJECT", "BOLD", "SERVICE", "HOME", "ABOUT", "CONTACT"]);

const SeoUpsertSchema = z.object({
  id: z.number().int().optional(),
  pageType: PageTypeSchema,
  pageId: z.number().int().nullable().optional(),
  title: z.string().min(1).max(60),
  metaDescription: z.string().min(1),
  keywords: z.string().nullable().optional(),
  ogTitle: z.string().nullable().optional(),
  ogDescription: z.string().nullable().optional(),
  ogImage: z.string().nullable().optional(),
  twitterCard: z.string().nullable().optional(),
  canonicalUrl: z.string().nullable().optional(),
  structuredData: z.any().nullable().optional(),
  robotsMeta: z.string().nullable().optional(),
});

export const POST = withErrorHandling(async (request: Request) => {
  const data = await parseJson(request, SeoUpsertSchema);

  // Find existing entry for (pageType, pageId) and update it, otherwise create.
  const existingEntry = await prisma.seometadata.findFirst({
    where: {
      pageType: data.pageType,
      pageId: data.pageId ?? null,
    },
  });

  const now = new Date();
  if (existingEntry) {
    const entry = await prisma.seometadata.update({
      where: { id: existingEntry.id },
      data: { ...data, updatedAt: now },
    });
    return ok(entry);
  }

  const entry = await prisma.seometadata.create({
    data: { ...data, updatedAt: now },
  });
  return ok(entry);
});

const SeoUpdateSchema = SeoUpsertSchema.extend({
  id: z.number().int(),
});

export const PUT = withErrorHandling(async (request: Request) => {
  const data = await parseJson(request, SeoUpdateSchema);
  const { id, ...updateData } = data;
  const metadata = await prisma.seometadata.update({
    where: { id },
    data: { ...updateData, updatedAt: new Date() },
  });
  return ok(metadata);
});

// DELETE: Use /api/seo/[id] instead
