import { NextResponse } from "next/server";
import { getServerSession } from "next-auth";
import { authOptions } from "@/lib/auth";
import { canManageHumanCapital } from "@/lib/human-capital";
import { publishHumanCapitalWorkspaceDraft } from "@/lib/human-capital/workspace";

export async function POST() {
  const session = await getServerSession(authOptions);
  if (!session?.user) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  if (!canManageHumanCapital(session.user.role, session.user.department)) {
    return NextResponse.json({ error: "Only owner/HC leaders can publish workspace." }, { status: 403 });
  }

  try {
    const config = await publishHumanCapitalWorkspaceDraft(session.user.id);
    return NextResponse.json({ ok: true, config });
  } catch (error) {
    const message = error instanceof Error ? error.message : "Failed to publish workspace.";
    return NextResponse.json({ error: message }, { status: 400 });
  }
}
