import { PagedResult, PageMeta } from './paging';

/**
 * Normalizes various pagination response formats into a unified PagedResult<T>.
 * Automatically merges any extra statistical fields inside `meta`.
 */
export function normalizePage<T>(raw: any, reqPage: number, perPage: number): PagedResult<T> {
  // 🟩 Case 1 — Spring Data style: { content, totalElements, number, size }
  if (raw && Array.isArray(raw.content) && typeof raw.totalElements === 'number') {
    return raw;
  }

  // 🟩 Case 2 — API or local mock: { data, meta: { total, ...extra } }
  if (raw && Array.isArray(raw.content) && raw.pageable?.total != null) {
    return raw
  }


  // 🟩 Case 4 — Direct array (no meta)
  if (Array.isArray(raw)) {
    const start = (reqPage - 1) * perPage;
    const data = (raw as T[]).slice(start, start + perPage);
    return {
      content: data,
      pageable:{
        pageNumber: raw.length/perPage,
        pageSize: perPage,
        total: raw.length
      },
      totalPages: raw.length/perPage,
      totalElements: raw.length
    };
  }

  // 🟩 Fallback — ensure consistency even with minimal info
  const data = Array.isArray(raw?.content) ? (raw.content as T[]) : [];
  const total = typeof raw?.total === 'number' ? raw.total : data.length ?? 0;

  return raw;
}
