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_COUNTRY, ESHOP } from '@/config/url-prefix'
import _ from 'lodash'

describe('Eshop Country - 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 country component when logged out', async () => {
    store = loggedOutStore()

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

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

    await flushPromises()

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

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

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

    router.replace = routerReplace

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

    router.push(ESHOP_COUNTRY + '/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(countryId).toBe('123')
    expect(updateSelectedCountry).toHaveBeenCalledTimes(1)
    expect(routerReplace).toHaveBeenCalledTimes(1)
    expect(clearShoppingData).toHaveBeenCalledTimes(1)
  })
})
