import { describe, expect, test, vi } from 'vitest'
import type { Query as PiniaOrmQuery } from 'pinia-orm'
import EqualFilter from '~/services/data/Filters/EqualFilter'
import type ApiResource from '~/models/ApiResource'

describe('constructor', () => {
  test('simple call', () => {
    const filter = new EqualFilter('foo', 123)

    expect(filter.field).toEqual('foo')
    expect(filter.filterValue).toEqual(123)
    expect(filter.reactiveFilter).toEqual(false)
  })

  test('simple call with reactive filters', () => {
    const filter = new EqualFilter('foo', 123, true)

    expect(filter.field).toEqual('foo')
    expect(filter.filterValue).toEqual(123)
    expect(filter.reactiveFilter).toEqual(true)
  })
})

describe('applyToPiniaOrmQuery', () => {
  test('simple call', () => {
    const filter = new EqualFilter('foo', 123)

    // @ts-ignore
    const piniaOrmQuery1 = vi.fn() as PiniaOrmQuery<ApiResource>

    // @ts-ignore
    const piniaOrmQuery2 = vi.fn() as PiniaOrmQuery<ApiResource>

    piniaOrmQuery1.where = vi.fn(() => piniaOrmQuery2)

    const result = filter.applyToPiniaOrmQuery(piniaOrmQuery1)

    expect(result).toEqual(piniaOrmQuery2)
    expect(piniaOrmQuery1.where).toHaveBeenCalledWith('foo', 123)
  })

  test('empty filter value', () => {
    const filter = new EqualFilter('foo', null)

    // @ts-ignore
    const piniaOrmQuery1 = vi.fn() as PiniaOrmQuery<ApiResource>

    piniaOrmQuery1.where = vi.fn()

    const result = filter.applyToPiniaOrmQuery(piniaOrmQuery1)

    expect(result).toEqual(piniaOrmQuery1)
    expect(piniaOrmQuery1.where).toHaveBeenCalledTimes(0)
  })
})

describe('getApiQueryPart', () => {
  test('simple call', () => {
    const filter = new EqualFilter('foo', 123)

    const result = filter.getApiQueryPart()

    expect(result).toEqual('foo=123')
  })

  test('empty filter value', () => {
    const filter = new EqualFilter('foo', null)

    const result = filter.getApiQueryPart()

    expect(result).toEqual('')
  })
})
