import { NextResponse } from "next/server";
import prisma from "@/lib/prisma";
import { z } from "zod";
import { requirePermission } from "@/lib/rbac";
import { getUserIdFromRequest } from "@/lib/auth";

const schema = z.object({ pinned: z.boolean(), order: z.number().int().nullable().optional() });

export async function POST(req: Request, context: { params: Promise<{ id: string }> }) {
  const { id } = await context.params;
  const body = await req.json();
  const parsed = schema.safeParse(body);
  if (!parsed.success) return NextResponse.json({ error: parsed.error.flatten() }, { status: 400 });
  const { pinned, order } = parsed.data;
  const userId = getUserIdFromRequest(req);
  try {
    await requirePermission({ userId, resource: "BOARD", action: "MODERATE" });
  } catch (e: any) {
    return NextResponse.json({ error: "Forbidden" }, { status: 403 });
  }
  const post = await prisma.post.update({
    where: { id },
    data: { isPinned: pinned, pinnedOrder: pinned ? order ?? 0 : null },
    select: { id: true, isPinned: true, pinnedOrder: true },
  });
  return NextResponse.json({ post });
}


