import { toFrappeFilterArray } from './listFilterUtils';

export interface FetchAllRowsParams {
  doctype: string;
  filters?: Record<string, any>;
  order_by?: string;
  fields?: string[];
}

/**
 * Page through frappe.client.get_list for CSV/Excel export (respects user permissions).
 */
export async function fetchAllRowsForExport(params: FetchAllRowsParams): Promise<any[]> {
  const { doctype, filters = {}, order_by = 'modified desc', fields } = params;
  const filterArray = toFrappeFilterArray(filters);
  const pageSize = 500;
  const all: any[] = [];
  let limit_start = 0;

  for (;;) {
    const requestBody: Record<string, unknown> = {
      doctype,
      filters: filterArray.length > 0 ? filterArray : {},
      fields: fields && fields.length > 0 ? fields : ['*'],
      order_by,
      limit_start,
      limit_page_length: pageSize,
    };

    const response = await fetch('/api/method/frappe.client.get_list', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
      credentials: 'include',
      body: JSON.stringify(requestBody),
    });

    const data = await response.json().catch(() => ({}));
    if (!response.ok) {
      throw new Error(data.message || data.exc || `Export fetch failed (${response.status})`);
    }

    const batch = data.message || [];
    if (!Array.isArray(batch) || batch.length === 0) break;
    all.push(...batch);
    if (batch.length < pageSize) break;
    limit_start += pageSize;
  }

  return all;
}
