import type { Query as PiniaOrmQuery } from 'pinia-orm'
import type { ApiFilter } from '~/types/data'
import ApiResource from '~/models/ApiResource'
import RefUtils from '~/services/utils/refUtils'

export default class PageFilter implements ApiFilter {
  page: Ref<number>
  itemsPerPage: Ref<number>

  /**
   * @param page
   * @param itemsPerPage
   */
  constructor(page: Ref<number>, itemsPerPage: Ref<number>) {
    this.page = page
    this.itemsPerPage = itemsPerPage
  }

  public applyToPiniaOrmQuery(
    query: PiniaOrmQuery<ApiResource>,
  ): PiniaOrmQuery<ApiResource> {
    const page = RefUtils.castToRef(this.page, false)

    const itemsPerPage = RefUtils.castToRef(this.itemsPerPage, false)

    return query
      .offset(itemsPerPage.value * (page.value - 1))
      .limit(itemsPerPage.value)
  }

  public getApiQueryPart(): string {
    return `page=${this.page.value}&itemsPerPage=${this.itemsPerPage.value}`
  }
}
