import { NextResponse } from "next/server";
import { getServerSession } from "next-auth";
import { authOptions } from "@/lib/auth";
import { listCaptureAssignees } from "@/lib/capture";

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

  const url = new URL(request.url);
  const department = url.searchParams.get("department");

  try {
    const assignees = await listCaptureAssignees({
      viewer: {
        userId: session.user.id,
        role: session.user.role,
        department: session.user.department ?? null,
      },
      requestedDepartment: department,
    });

    return NextResponse.json({ ok: true, assignees });
  } catch (error) {
    const message = error instanceof Error ? error.message : "Unable to list capture assignees.";
    if (message === "Forbidden") {
      return NextResponse.json({ error: "Forbidden" }, { status: 403 });
    }

    return NextResponse.json({ error: message }, { status: 400 });
  }
}
