import apiClient from "@/lib/api/client";
import type { ApiResponse, QueryParams } from "@/lib/api/types";
import type { ParticipantPaymentRecord } from "@/features/opportunities/participantPaymentRecord";

/**
 * BE-125 — the organizer's participants-and-payments table, and the refund
 * that goes with it.
 *
 * Both are `api.approved-org` and owner-only: the controller compares
 * `created_by` against the caller and answers **403** otherwise, for the list
 * as well as the refund.
 */

/**
 * Paginated, through the standard `meta.pagination` envelope. Every
 * registration appears, paid or not — the row carries `payment_status: null`
 * when there is no transaction behind it.
 */
export const getParticipantsPayments = (
  opportunityId: string | number,
  params?: QueryParams
): Promise<ApiResponse<ParticipantPaymentRecord[]>> =>
  apiClient
    .get(`/learn-serve-opportunities/${opportunityId}/participants-payments/`, {
      params,
    })
    .then((r) => r.data);

/** `paginateQuery()` caps `limit` at 100. */
const ALL_PAGES_LIMIT = 100;

/**
 * Every page, collected. The screen needs the whole list at once: the totals
 * row is a sum over every participant and the search/date filters run over
 * all of them, and the server offers neither. A development opportunity's
 * capacity keeps this to a request or two.
 */
export async function getAllPages<T>(
  fetchPage: (params: QueryParams) => Promise<ApiResponse<T[]>>
): Promise<T[]> {
  const rows: T[] = [];
  for (let page = 1; page <= 50; page += 1) {
    const response = await fetchPage({ page, limit: ALL_PAGES_LIMIT });
    const batch = response?.data ?? [];
    rows.push(...batch);
    const totalPages = response?.meta?.pagination?.total_pages;
    if (totalPages ? page >= totalPages : batch.length < ALL_PAGES_LIMIT) break;
  }
  return rows;
}

