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

export default class EqualFilter extends AbstractFilter implements ApiFilter {
  field: string
  filterValue: string | number | null | Ref<string | number | null>

  /**
   * @param field
   * @param value
   * @param reactiveFilter
   */
  constructor(
    field: string,
    value: string | number | null | Ref<string | number | null>,
    reactiveFilter: boolean = false,
  ) {
    super(reactiveFilter)
    this.field = field
    this.filterValue = value
  }

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

    if (filterValue.value === null) {
      return query
    }

    return query.where(this.field, filterValue.value)
  }

  public getApiQueryPart(): string {
    const filterValue = RefUtils.castToRef(
      this.filterValue,
      this.reactiveFilter,
    )

    if (filterValue.value === null) {
      return ''
    }

    return `${this.field}=${filterValue.value}`
  }
}
