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,
      description: body.description || "",
      content: body.content || "",
      category: body.category || "Commercial",
      location: body.location || null,
      completionDate: body.completionDate || null,
      client: body.client || null,
      images: JSON.stringify(body.images || []),
      videos: JSON.stringify(body.videos || []),
      isFeatured: body.isFeatured ?? false,
      isEnabled: body.isEnabled ?? true,
      metaTitle: body.metaTitle || null,
      metaDescription: body.metaDescription || null,
    };
    if (body.slug) {
      const slug = slugify(body.slug);
      if (!slug) return fail("A valid slug is required");
      const existing = await db.project.findUnique({ where: { slug } });
      if (existing && existing.id !== id) return fail("A project with this slug already exists");
      data.slug = slug;
    }
    const project = await db.project.update({ where: { id }, data });
    return ok({ project });
  } catch (e) {
    console.error(e);
    return fail("Failed to update project", 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.project.delete({ where: { id } });
    return ok({ ok: true });
  } catch (e) {
    return fail("Failed to delete project", 500);
  }
}
