import 'nprogress/nprogress.css';
import NProgress from 'nprogress';
import store from '@/vue/store';
import i18n from '@/vue/i18n';
import { loggerVue } from '@/plugins/logger';
import { guardAuth, guardPlan } from './guards';
import { checkShopeeApiValid, initStore } from './tasks';

/**
 * @typedef {import('vue-router').default} VueRouterCore
 */

const guardProgress = (to, from, next) => {
  NProgress.start();
  next();
};

const afterTitle = (to) => {
  const { pageTitleKey } = to.meta;

  if (pageTitleKey) {
    store.dispatch('SetAppTitle', i18n.t(pageTitleKey));
  }
};

/**
 * @param {VueRouterCore} router
 * @returns {VueRouterCore}
 */
const middlewareLoader = (router) => {
  router.beforeEach(guardAuth);
  router.beforeEach(guardPlan);
  router.beforeEach(guardProgress);
  router.afterEach(() => NProgress.done());
  router.afterEach(afterTitle);

  store.dispatch('RouterInit').then(() => {
    checkShopeeApiValid().catch(() => {});

    setTimeout(() => {
      initStore().catch((error) => {
        loggerVue.error({ msg: 'STORE_INIT_ERROR', error });
      });
    }, 1000);
  });

  return router;
};

export default middlewareLoader;
