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

export async function PUT(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
  const session = await requireAdminSession();
  if (!session) return unauthorized();
  try {
    const { id } = await params;
    const body = await req.json();
    const data: any = {
      title: body.title,
      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,
    };
    if (body.slug) data.slug = slugify(body.slug);
    const service = await db.service.update({ where: { id }, data });
    return ok({ service });
  } catch (e) {
    console.error(e);
    return fail("Failed to update service", 500);
  }
}

export async function DELETE(_req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
  const session = await requireAdminSession();
  if (!session) return unauthorized();
  try {
    const { id } = await params;
    await db.service.delete({ where: { id } });
    return ok({ ok: true });
  } catch (e) {
    return fail("Failed to delete service", 500);
  }
}
