import { http } from '@/api'
import type { PaginatedResponse } from '@/types/api'

const API_PAGE_SIZE = 200

/** 服务端 page/per_page 分页；-1 时拉取全部页 */
export async function fetchPagePerPage<T>(
  path: string,
  params: Record<string, unknown>,
  page: number,
  itemsPerPage: number,
): Promise<{ items: T[]; total: number }> {
  if (itemsPerPage !== -1) {
    const res = await http.get<PaginatedResponse<T>>(path, {
      ...params,
      page,
      per_page: itemsPerPage,
    })
    return { items: res.items || [], total: res.total ?? 0 }
  }

  const all: T[] = []
  let p = 1
  let pages = 1
  let total = 0
  do {
    const res = await http.get<PaginatedResponse<T>>(path, {
      ...params,
      page: p,
      per_page: API_PAGE_SIZE,
    })
    all.push(...(res.items || []))
    total = res.total ?? all.length
    pages = res.pages ?? 1
    p += 1
  } while (p <= pages)
  return { items: all, total }
}

/** 服务端 limit/offset 分页；-1 时拉取全部 */
export async function fetchLimitOffset<T>(
  fetchPage: (limit: number, offset: number) => Promise<{ items: T[]; total: number }>,
  page: number,
  itemsPerPage: number,
): Promise<{ items: T[]; total: number }> {
  if (itemsPerPage !== -1) {
    const offset = (page - 1) * itemsPerPage
    return fetchPage(itemsPerPage, offset)
  }

  const all: T[] = []
  let offset = 0
  let total = 0
  do {
    const res = await fetchPage(API_PAGE_SIZE, offset)
    all.push(...(res.items || []))
    total = res.total ?? all.length
    if (!res.items.length || all.length >= total) break
    offset += API_PAGE_SIZE
  } while (true)
  return { items: all, total }
}
