import { NextRequest, NextResponse } from "next/server";
import { requirePermission, getAdminAuditContext } from "@/lib/admin/auth";
import { db } from "@/lib/admin/db";

export const dynamic = "force-dynamic";

/**
 * PATCH /api/admin/categories/[id]
 * Updates an existing category in MongoDB.
 */
export async function PATCH(
  req: NextRequest,
  context: { params: Promise<{ id: string }> }
) {
  try {
    const ctx = await requirePermission("posts.edit", req);
    const { id } = await context.params;
    const body = await req.json();

    const updates: any = {};
    if (body.name !== undefined) {
      const name = body.name.trim();
      if (!name) {
        return NextResponse.json({ error: "Category name cannot be empty." }, { status: 400 });
      }
      updates.name = name;
    }

    if (body.slug !== undefined) {
      const slug = body.slug.trim().toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/(^-|-$)+/g, "");
      if (!slug) {
        return NextResponse.json({ error: "Category slug cannot be empty." }, { status: 400 });
      }
      updates.slug = slug;
    }

    if (body.description !== undefined) {
      updates.description = body.description.trim();
    }

    const auditCtx = await getAdminAuditContext(req);
    const updated = await db.updateCategory(id, updates);

    await db.logContentEvent({
      actorId: ctx.user.id,
      actorName: ctx.user.name,
      actorEmail: ctx.user.email,
      actorRole: ctx.user.role,
      location: auditCtx.location || null,
      postId: null,
      postTitle: null,
      postSlug: null,
      action: "CATEGORY_UPDATED",
      details: {
        categoryId: updated.id,
        categoryName: updated.name,
        categorySlug: updated.slug,
        note: `Updated category "${updated.name}" (${updated.slug})`,
      },
    });

    return NextResponse.json({ category: updated });
  } catch (err: any) {
    console.error("[PATCH /api/admin/categories/[id]] Error:", err);
    return NextResponse.json(
      { error: err.message || "Failed to update category." },
      { status: err.status || 400 }
    );
  }
}

/**
 * DELETE /api/admin/categories/[id]
 * Deletes a category if no posts are actively assigned to it.
 */
export async function DELETE(
  req: NextRequest,
  context: { params: Promise<{ id: string }> }
) {
  try {
    const ctx = await requirePermission("posts.edit", req);
    const { id } = await context.params;

    const existing = await db.getCategoryById(id);
    if (!existing) {
      return NextResponse.json({ error: "Category not found." }, { status: 404 });
    }

    const auditCtx = await getAdminAuditContext(req);
    await db.deleteCategory(id);

    await db.logContentEvent({
      actorId: ctx.user.id,
      actorName: ctx.user.name,
      actorEmail: ctx.user.email,
      actorRole: ctx.user.role,
      location: auditCtx.location || null,
      postId: null,
      postTitle: null,
      postSlug: null,
      action: "CATEGORY_DELETED",
      details: {
        categoryId: existing.id,
        categoryName: existing.name,
        categorySlug: existing.slug,
        note: `Deleted category "${existing.name}" (${existing.slug})`,
      },
    });

    return NextResponse.json({ success: true });
  } catch (err: any) {
    console.error("[DELETE /api/admin/categories/[id]] Error:", err);
    return NextResponse.json(
      { error: err.message || "Failed to delete category." },
      { status: err.status || 400 }
    );
  }
}
