import { createAppLocalVue } from '@/../tests/utils' // should be the first to implement default mocks
import App from '@/app/App.vue'
import { loggedInStore, loggedOutStore } from '@/../tests/factories/auth-store'
import { shallowMount, mount } from '@vue/test-utils'
import flushPromises from 'flush-promises'
import { store as appStore } from '@/store'
import { ESHOP_LANGUAGE, ESHOP } from '@/config/url-prefix'
import _ from 'lodash'

describe('Eshop Language - Routing', () => {
  let store
  let localVue
  let router
  let SecurityConfig

  beforeEach(async () => {
    jest.resetModules()
    jest.clearAllMocks()

    router = await require('@/router').default

    SecurityConfig = await require('@/config/security').default

    SecurityConfig.router = router

    localVue = createAppLocalVue()

    await flushPromises()
  })

  it('Should not render language component when logged out', async () => {
    store = loggedOutStore()

    const wrapper = shallowMount(App, {
      localVue,
      router,
      store: store,
    })

    router.push(ESHOP_LANGUAGE + '/123').catch(() => {})

    await flushPromises()

    expect(wrapper.vm.$route.path).not.toMatch(ESHOP_LANGUAGE)
  })

  it(`Should render language component when logged in and have
   change the selected country then routed back to ESHOP`, async () => {
    // called on mount
    let languageId
    let updateSelectedLanguage = jest.fn((arg1, arg2) => {
      languageId = arg2
    }) // to update the selected country
    let routerReplace = jest.fn() // to go back to eshop

    store = loggedInStore(
      _.merge(appStore, {
        modules: {
          locationModule: {
            actions: {
              updateSelectedLanguage,
            },
          },
        },
      })
    )

    router.replace = routerReplace

    const wrapper = mount(App, {
      localVue,
      router,
      store: store,
      mocks: {
        $t: jest.fn(),
      },
    })

    router.push(ESHOP_LANGUAGE + '/123')

    await flushPromises()

    expect(wrapper.isVueInstance()).toBeTruthy()

    // it should have changed the selected country and routed back to ESHOP
    expect(wrapper.vm.$route.path).toMatch(ESHOP)
    expect(languageId).toBe('123')
    expect(routerReplace).toHaveBeenCalledTimes(1)
  })
})
