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

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

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

  const { searchParams } = new URL(request.url);

  try {
    const rollup = await getOwnerCaptureRollup({
      viewer: {
        userId: session.user.id,
        role: session.user.role,
        department: session.user.department ?? null,
      },
      weekStartInput: searchParams.get("weekStart"),
    });

    return NextResponse.json(rollup);
  } catch (error) {
    const message = error instanceof Error ? error.message : "Failed to load owner capture rollup.";
    return NextResponse.json({ error: message }, { status: 400 });
  }
}
