import { api } from './api';

interface PaginatedResponse<T> {
  data: T[];
  nextCursor: string | null;
  hasMore: boolean;
}

/**
 * Fetch all items from a paginated endpoint using cursor-based pagination.
 * Accumulates all pages into a single array.
 */
export async function fetchAll<T>(
  basePath: string,
  params: Record<string, string> = {},
  limit = 100,
): Promise<T[]> {
  const all: T[] = [];
  let cursor: string | null = null;

  do {
    const qp: Record<string, string> = {
      ...params,
      limit: String(limit),
    };
    if (cursor) {
      qp.cursor = cursor;
    }

    const qs = new URLSearchParams(qp).toString();
    const res = await api.get<PaginatedResponse<T>>(
      `${basePath}?${qs}`,
    );

    all.push(...res.data);
    cursor = res.hasMore ? res.nextCursor : null;
  } while (cursor);

  return all;
}
