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

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

  if (!canAccessHumanCapital(session.user.role, session.user.department)) {
    return NextResponse.json({ error: "Forbidden" }, { status: 403 });
  }

  const { searchParams } = new URL(request.url);
  const mode = searchParams.get("mode") === "draft" ? "draft" : "published";

  if (mode === "draft" && !canManageHumanCapital(session.user.role, session.user.department)) {
    return NextResponse.json({ error: "Only owner/HC leaders can view draft config." }, { status: 403 });
  }

  const config = await getHumanCapitalWorkspaceConfig({ mode, actorId: session.user.id });
  return NextResponse.json({ ok: true, config });
}

export async function PUT(request: Request) {
  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 edit workspace." }, { status: 403 });
  }

  const body = (await request.json().catch(() => ({}))) as { tabs?: unknown; changeSummary?: string | null };
  if (!body.tabs) {
    return NextResponse.json({ error: "tabs are required." }, { status: 400 });
  }

  try {
    const config = await updateHumanCapitalWorkspaceDraft({
      tabs: body.tabs,
      actorId: session.user.id,
      changeSummary: body.changeSummary ?? null,
    });

    return NextResponse.json({ ok: true, config });
  } catch (error) {
    const message = error instanceof Error ? error.message : "Failed to update workspace config.";
    return NextResponse.json({ error: message }, { status: 400 });
  }
}
