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

export const GET = withErrorHandling(
  async (request: Request, { params }: { params: Promise<{ id: string }> }) => {
    const id = await parseIdParam(params);
    const metadata = await prisma.seometadata.findUnique({
      where: { id },
    });

    if (!metadata) throw new HttpError("SEO metadata not found", { status: 404 });
    return ok(metadata);
  },
);

const SeoUpdateSchema = z.object({
  title: z.string().min(1).max(60).optional(),
  metaDescription: z.string().min(1).optional(),
  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 PUT = withErrorHandling(
  async (request: Request, { params }: { params: Promise<{ id: string }> }) => {
    const id = await parseIdParam(params);
    const updateData = await parseJson(request, SeoUpdateSchema);
    const metadata = await prisma.seometadata.update({
      where: { id },
      data: { ...updateData, updatedAt: new Date() },
    });
    return ok(metadata);
  },
);

export const DELETE = withErrorHandling(
  async (request: Request, { params }: { params: Promise<{ id: string }> }) => {
    const id = await parseIdParam(params);
    await prisma.seometadata.delete({
      where: { id },
    });
    return ok({ success: true });
  },
);
