import { Prisma } from "@/generated/prisma/client"
import { PaginatedResult } from "@/lib/types"

//eslint-disable-next-line
type PaginationArgs<T> = {
  model: any // prisma.<model>
  where?: Prisma.Enumerable<any> // filtros
  page?: number
  pageSize?: number
  orderBy?: any
  include?: Prisma.Enumerable<any>
  select?: Prisma.Enumerable<any>
}

export async function paginate<T>({
  model,
  where = {},
  page = 1,
  pageSize = 10,
  orderBy = { createdAt: "desc" },
  include,
  select,
}: PaginationArgs<T>): Promise<PaginatedResult<T>> {
  const skip = (page - 1) * pageSize

  const [data, totalItems] = await Promise.all([
    model.findMany({
      where,
      skip,
      take: pageSize,
      orderBy,
      include,
      select,
    }),
    model.count({ where }),
  ])

  return {
    data,
    totalItems,
    totalPages: Math.ceil(totalItems / pageSize),
    currentPage: page,
    pageSize,
  }
}
