import { NextRequest } from "next/server";
import { db } from "@/lib/db";
import { requireAdminSession, unauthorized, ok, fail, slugify } from "@/lib/admin-api";

export async function POST(req: NextRequest) {
  const session = await requireAdminSession();
  if (!session) return unauthorized();
  try {
    const body = await req.json();
    const slug = body.slug ? slugify(body.slug) : slugify(body.title);
    const existing = await db.service.findUnique({ where: { slug } });
    if (existing) return fail("A service with this slug already exists");

    const service = await db.service.create({
      data: {
        title: body.title,
        slug,
        shortDescription: body.shortDescription || "",
        description: body.description || "",
        icon: body.icon || "Wrench",
        image: body.image || null,
        features: JSON.stringify(body.features || []),
        isEnabled: body.isEnabled ?? true,
        order: body.order ?? 0,
        metaTitle: body.metaTitle || null,
        metaDescription: body.metaDescription || null,
      },
    });
    return ok({ service });
  } catch (e) {
    console.error(e);
    return fail("Failed to create service", 500);
  }
}
