import type { Query as PiniaOrmQuery } from 'pinia-orm'
import type { ApiFilter } from '~/types/data'
import ApiResource from '~/models/ApiResource'
import { ORDER_BY_DIRECTION } from '~/types/enum/data'
import StringUtils from '~/services/utils/stringUtils'

export default class OrderBy implements ApiFilter {
  field: string
  mode: ORDER_BY_DIRECTION

  /**
   * @param field
   * @param mode
   */
  constructor(
    field: string,
    mode: ORDER_BY_DIRECTION = ORDER_BY_DIRECTION.ASC,
  ) {
    this.field = field
    this.mode = mode
  }

  public applyToPiniaOrmQuery(
    query: PiniaOrmQuery<ApiResource>,
  ): PiniaOrmQuery<ApiResource> {
    return query.orderBy(
      (instance) => StringUtils.normalize(instance[this.field]),
      this.mode,
    )
  }

  public getApiQueryPart(): string {
    return `order[${this.field}]=${this.mode}`
  }
}
