import { NextRequest, NextResponse } from "next/server";
import { addAudit, readDb, writeDb } from "@/lib/store";

export async function POST(req: NextRequest, { params }: { params: { id: string } }) {
  const body = await req.json().catch(() => ({}));
  const apiBoardId = String(body.apiBoardId || "").trim();
  if (!apiBoardId) return NextResponse.json({ error: "apiBoardId required" }, { status: 400 });

  const db = await readDb();
  const board = db.boards.find((item) => item.id === params.id);
  if (!board) return NextResponse.json({ error: "board not found" }, { status: 404 });

  const duplicate = db.boards.find((item) => item.id !== board.id && item.apiBoardId === apiBoardId);
  if (duplicate) return NextResponse.json({ error: `apiBoardId already bound to ${duplicate.name}` }, { status: 409 });

  board.apiBoardId = apiBoardId;
  board.updatedAt = new Date().toISOString();
  addAudit(db, {
    type: "content",
    actor: "user",
    title: "手动绑定 Pinterest 图板",
    detail: `${board.name} -> ${apiBoardId}`,
    status: "completed",
  });
  await writeDb(db);

  return NextResponse.json({ board });
}
