import type { ApiResponse, FaqItem } from "@/lib/api/types";

/**
 * `FaqController::index()` reads `PageParams::limit($request, 10, 100)`: a
 * larger `limit` is capped at 100, not refused. Asking for `limit=1000` (what
 * the FAQ page used to send) therefore still answered one page of 100, and
 * every question the administration added after the hundredth never showed.
 */
export const FAQ_PAGE_LIMIT = 100;

/** Safety stop for a malformed `total_pages`: 5,000 questions. */
const MAX_FAQ_PAGES = 50;

/**
 * Every FAQ the administration published (PDF p.32), across the pages of
 * `GET /faqs/`. Pure and transport-agnostic so the server page (native
 * `fetch`) and the client component (axios) share it without crossing the
 * server/client boundary. A failed page rejects, exactly like the single
 * request did. A response without `meta.pagination` counts as one page.
 */
export async function collectFaqPages(
  fetchPage: (page: number, limit: number) => Promise<ApiResponse<FaqItem[]>>
): Promise<ApiResponse<FaqItem[]>> {
  const first = await fetchPage(1, FAQ_PAGE_LIMIT);
  const rows = [...(first?.data ?? [])];
  const totalPages = Math.min(first?.meta?.pagination?.total_pages ?? 1, MAX_FAQ_PAGES);
  for (let page = 2; page <= totalPages; page += 1) {
    const next = await fetchPage(page, FAQ_PAGE_LIMIT);
    rows.push(...(next?.data ?? []));
  }
  return { ...first, data: rows };
}
