import * as _ from 'lodash'
import { Query } from '@vuex-orm/core'
import { createStore } from '~/tests/unit/Helpers'
import User from '~/tests/unit/fixture/models/User'
import { queryHelper } from '~/services/store/query'
import { AnyStore } from '~/types/interfaces'

let store:AnyStore, query:Query

beforeEach(() => {
  store = createStore()
  query = store.$repo(User).query()
})

describe('getItem()', () => {
  it('should throw an error if the Item is not found', () => {
    expect(() => queryHelper.getItem(query, 1)).toThrowError('item not found')
  })

  it('should return an Item', () => {
    const user = store.$repo(User).make()
    store.$repo(User).save(user)
    expect(queryHelper.getItem(query, 1)).toStrictEqual(user)
  })
})

describe('getCollection()', () => {
  it('should return an array of Items', () => {
    const UsersArray:Array<User> = []
    const user = store.$repo(User).make()
    UsersArray.push(user)
    store.$repo(User).save(user)

    const user2 = _.cloneDeep(user)
    user2.id = 2
    user2.name = 'Foo Bar'
    UsersArray.push(user2)
    store.$repo(User).save(user2)

    expect(queryHelper.getCollection(query)).toStrictEqual(UsersArray)
  })
})

describe('getFlattenEntry()', () => {
  it('should throw an error if the Item is not found', () => {
    expect(() => queryHelper.getFlattenEntry(query, 1)).toThrowError('item not found')
  })

  it('should find an Item and return a JSON flatten object', () => {
    const user = store.$repo(User).make()
    store.$repo(User).save(user)
    expect(queryHelper.getFlattenEntry(query, 1)).toStrictEqual({ id: 1, name: 'John Doe' })
  })
})

describe('getFlattenEntries()', () => {
  it('should find an Item and return a JSON flatten object', () => {
    const user = store.$repo(User).make()
    store.$repo(User).save(user)
    const user2 = _.cloneDeep(user)
    user2.id = 2
    user2.name = 'Foo Bar'
    store.$repo(User).save(user2)

    expect(queryHelper.getFlattenEntries(query)).toStrictEqual([{ id: 1, name: 'John Doe' }, { id: 2, name: 'Foo Bar' }])
  })
})
