import { z } from "zod";
import prisma from "@/server/db/prisma";
import { requireAdmin } from "@/server/auth/requireAdmin";
import { parseJson } from "@/server/http/parse";
import { ok } from "@/server/http/response";
import { DeleteByIdSchema } from "@/server/http/schemas";
import { withErrorHandling } from "@/server/http/withErrorHandling";
import { setCacheHeaders } from "@/server/http/cacheHeaders";

// GET: Fetch all services
export const GET = withErrorHandling(async () => {
  const services = await prisma.service.findMany({
    select: {
      id: true,
      title: true,
      description: true,
      icon: true,
    },
  });
  const response = ok(services);
  return setCacheHeaders(response, "medium");
});

// POST: Add or update a service
const ServiceUpsertSchema = z.object({
  id: z.number().int().optional(),
  title: z.string().min(1).max(200),
  description: z.string().min(1).max(2000),
  icon: z.string().min(1).max(100),
});

export const POST = withErrorHandling(async (request: Request) => {
  await requireAdmin(request);
  const { id, title, description, icon } = await parseJson(request, ServiceUpsertSchema);

  if (id) {
    const updatedService = await prisma.service.update({
      where: { id },
      data: { title, description, icon },
      select: {
        id: true,
        title: true,
        description: true,
        icon: true,
      },
    });
    return ok(updatedService);
  }

  const newService = await prisma.service.create({
    data: { title, description, icon },
    select: {
      id: true,
      title: true,
      description: true,
      icon: true,
    },
  });
  return ok(newService);
});

// DELETE: Remove a service
export const DELETE = withErrorHandling(async (request: Request) => {
  await requireAdmin(request);
  const { id } = await parseJson(request, DeleteByIdSchema);
  await prisma.service.delete({ where: { id } });
  return ok({ message: "Service deleted successfully" });
});
