import { NextResponse } from "next/server";
import { getServerSession } from "next-auth";
import { authOptions } from "@/lib/auth";
import { getCaptureBoard } 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 weekStart = url.searchParams.get("weekStart");
  const department = url.searchParams.get("department");

  try {
    const board = await getCaptureBoard({
      viewer: {
        userId: session.user.id,
        role: session.user.role,
        department: session.user.department ?? null,
      },
      weekStartInput: weekStart,
      requestedDepartment: department,
      filters: {
        initiativeId: url.searchParams.get("initiativeId") ?? undefined,
        taskId: url.searchParams.get("taskId") ?? undefined,
        uploadedById: url.searchParams.get("uploadedById") ?? undefined,
        from: url.searchParams.get("from") ?? undefined,
        to: url.searchParams.get("to") ?? undefined,
        query: url.searchParams.get("q") ?? undefined,
      },
    });

    return NextResponse.json(board);
  } catch (error) {
    const message = error instanceof Error ? error.message : "Failed to load capture board.";
    if (message === "Forbidden") {
      return NextResponse.json({ error: "Forbidden" }, { status: 403 });
    }

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