import { NextRequest, NextResponse } from "next/server";
import { requirePermission, getAdminAuditContext } from "@/lib/admin/auth";
import { blogService } from "@/lib/blog-service";

export const dynamic = "force-dynamic";

/**
 * POST /api/admin/posts/[id]/duplicate
 * Duplicates a post into a new DRAFT article with unique slug and copied metadata.
 */
export async function POST(
  req: NextRequest,
  context: { params: Promise<{ id: string }> }
) {
  try {
    const ctx = await requirePermission("posts.create", req);
    const { id } = await context.params;
    const auditCtx = await getAdminAuditContext(req);

    const duplicated = await blogService.duplicate(id, {
      ...ctx.user,
      location: auditCtx.location,
    });
    return NextResponse.json({ post: duplicated }, { status: 201 });
  } catch (err: any) {
    console.error("[POST /api/admin/posts/[id]/duplicate] Error:", err);
    return NextResponse.json(
      { error: err.message || "Failed to duplicate article" },
      { status: err.status || 500 }
    );
  }
}
