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();
    if (!body.title || !String(body.title).trim()) return fail("Title is required");
    if (!body.description || !String(body.description).trim()) return fail("Description is required");

    const slug = body.slug ? slugify(body.slug) : slugify(body.title);
    if (!slug) return fail("Could not generate a valid slug");

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

    const industry = await db.industry.create({
      data: {
        title: String(body.title).trim(),
        slug,
        description: String(body.description).trim(),
        image: body.image || null,
        icon: body.icon || null,
        order: typeof body.order === "number" ? body.order : Number(body.order) || 0,
        isEnabled: body.isEnabled ?? true,
      },
    });
    return ok({ industry });
  } catch (e) {
    console.error(e);
    return fail("Failed to create industry", 500);
  }
}
