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 || "");
    if (!slug) return fail("A valid title or slug is required");

    const existing = await db.project.findUnique({ where: { slug } });
    if (existing) return fail("A project with this slug already exists");

    const project = await db.project.create({
      data: {
        title: body.title,
        slug,
        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,
      },
    });
    return ok({ project });
  } catch (e) {
    console.error(e);
    return fail("Failed to create project", 500);
  }
}
