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

describe('constructor', () => {
  test('simple call', () => {
    const filter = new PageFilter(ref(1), ref(10))

    expect(filter.page.value).toEqual(1)
    expect(filter.itemsPerPage.value).toEqual(10)
  })
})

describe('applyToPiniaOrmQuery', () => {
  test('simple call', () => {
    const filter = new PageFilter(ref(1), ref(10))

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

    piniaOrmQuery1.offset = vi.fn(() => piniaOrmQuery2)
    piniaOrmQuery2.limit = vi.fn(() => piniaOrmQuery3)

    const result = filter.applyToPiniaOrmQuery(piniaOrmQuery1)

    expect(result).toEqual(piniaOrmQuery3)

    expect(piniaOrmQuery1.offset).toHaveBeenCalledWith(0)
    expect(piniaOrmQuery2.limit).toHaveBeenCalledWith(10)
  })

  test('with other page number', () => {
    const filter = new PageFilter(ref(2), ref(20))

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

    piniaOrmQuery1.offset = vi.fn(() => piniaOrmQuery2)
    piniaOrmQuery2.limit = vi.fn(() => piniaOrmQuery3)

    const result = filter.applyToPiniaOrmQuery(piniaOrmQuery1)

    expect(result).toEqual(piniaOrmQuery3)

    expect(piniaOrmQuery1.offset).toHaveBeenCalledWith(20)
    expect(piniaOrmQuery2.limit).toHaveBeenCalledWith(20)
  })
})

describe('getApiQueryPart', () => {
  test('simple call', () => {
    const filter = new PageFilter(ref(1), ref(10))

    const result = filter.getApiQueryPart()

    expect(result).toEqual('page=1&itemsPerPage=10')
  })
})
