import { ref, computed } from 'vue'

interface UsePaginationOptions {
  pageSize?: number
  fetchFn: (page: number) => Promise<void>
}

/**
 * Offset-based pagination composable.
 *
 * 注意：keyset 分页模式（date/cited/title/journal/first_author 排序）由 SearchView
 * 独立管理 keysetCursors/keysetHasMore/keysetPage。此 composable 的 totalPages/hasMore
 * 在 keyset 模式下语义不准确（keyset 用 has_more 标志而非总页数判断），由调用方覆盖使用。 */
export function usePagination(opts: UsePaginationOptions) {
  const { fetchFn, pageSize: initialPageSize = 20 } = opts
  const page = ref(1)
  const pageSize = ref(initialPageSize)
  const total = ref(0)

  const totalPages = computed(() => Math.max(1, Math.ceil(total.value / pageSize.value)))
  const hasMore = computed(() => page.value < totalPages.value)

  async function goToPage(n: number) {
    const prev = page.value
    page.value = n
    try {
      await fetchFn(n)
    } catch {
      page.value = prev
    }
  }

  return { page, pageSize, total, totalPages, hasMore, goToPage }
}
