import { NextRequest, NextResponse } from "next/server";
import { getProperties, getPropertiesCount } from "@/app/portfolio/[slug]/utils";
import { FilterGroups } from "@/app/utils/propertyFilters";

// The property list paginates at 7 rows/page and isn't scrolled through in bulk,
// so a small initial page keeps the (join-heavy) query fast. Export fetches its
// own larger batch on demand (see EXPORT_LIMIT in PropertyTable).
const DEFAULT_LIMIT = 250;

export async function POST(req: NextRequest) {
  const body = await req.json();

  const portfolioId = body.portfolioId;
  const filterGroups: FilterGroups = body.filters ?? [];
  const limit: number = body.limit ?? DEFAULT_LIMIT;
  const offset: number = body.offset ?? 0;

  if (!portfolioId) {
    return NextResponse.json(
      { error: "Missing portfolioId" },
      { status: 400 }
    );
  }

  // Only compute the total count on the first page — it's expensive and doesn't change
  const [data, total] = await Promise.all([
    getProperties(portfolioId, limit, offset, filterGroups),
    offset === 0 ? getPropertiesCount(portfolioId, filterGroups) : Promise.resolve(null),
  ]);

  return NextResponse.json({ data, total });
}
