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();
    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 data: any = {
      title: String(body.title).trim(),
      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,
    };

    if (body.slug) {
      const newSlug = slugify(body.slug);
      if (newSlug) {
        const clash = await db.industry.findFirst({ where: { slug: newSlug, NOT: { id } } });
        if (clash) return fail("An industry with this slug already exists");
        data.slug = newSlug;
      }
    }

    const industry = await db.industry.update({ where: { id }, data });
    return ok({ industry });
  } catch (e) {
    console.error(e);
    return fail("Failed to update industry", 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.industry.delete({ where: { id } });
    return ok({ ok: true });
  } catch (e) {
    return fail("Failed to delete industry", 500);
  }
}
