import Vue from 'vue';
import Vuex from 'vuex';
import createPersistedState from 'vuex-persistedstate';
import { loggerVue } from '@/plugins/logger';
import modules from './modules/loader';

Vue.use(Vuex);

const listenerStore = (store) => {
  const originalRegisterModule = store.registerModule;

  store.registerModule = function (...args) {
    const [path] = args;

    const moduleName = Array.isArray(path) ? path.join('/') : path;

    loggerVue.info({
      msg: 'VUEX_MODULE_REGISTER',
      moduleName,
    });

    return originalRegisterModule.apply(this, args);
  };

  const originalDispatch = store.dispatch;

  store.dispatch = function (type, payload) {
    if (!store._actions[type]) {
      loggerVue.error({
        msg: 'VUEX_ACTION_NOT_FOUND',
        type,
      });
    }
    return originalDispatch.call(this, type, payload);
  };

  const originalGetters = new Proxy(store.getters, {
    get(target, prop) {
      if (!(prop in target)) {
        loggerVue.error({
          msg: 'VUEX_GETTER_NOT_FOUND',
          getter: prop,
        });
        return undefined;
      }
      return target[prop];
    },
  });

  store.getters = originalGetters;

  const originalCommit = store.commit;

  store.commit = function (type, payload) {
    if (!store._mutations[type]) {
      loggerVue.error({
        msg: 'VUEX_MUTATION_NOT_FOUND',
        type,
      });
    }
    return originalCommit.call(this, type, payload);
  };
};

const persistStoreLocalStorage = createPersistedState({
  key: 'vuex-store-persist',
  storage: window.localStorage,
  paths: [
    // user
    'user.id',
    'user.userData',
    'user.extensionPlan',
    'user.token',
    'user.username',
    'user.profileId',
    // app
    'app.isBetaMode',
    'app.useShopManager',
    'app.indentify',
    'app.extensionInfo',
    'setting',
    // shopee seller
    'shopee_seller.ref',
    'shopee_seller.id',
    'shopee_seller.name',
    'shopee_seller.image',
    'shopee_seller.shopWarehouse',
    'shopee_seller.spccds',
    'shopee_seller.spcf',
    'shopee_seller.lastestSync',
    'shopee_seller.shopInfo',
    'shopee_seller.shopSync',
    'shopee_seller.shopLogistic',
    // shopee
    'shopee_product.clone.payload',
    'shopee_affiliate',
    'shopee_flashsale.schedulerJob.auto',
    'shopee_flashsale.campaignJob.auto',
    'shopee_keyword',
    // tiktok
    'tiktok',
    'lazada',
  ],
});

const persistStoreSessionStorage = createPersistedState({
  key: 'vuex-store-persist',
  storage: window.sessionStorage,
  paths: [
    'shopee_flashsale.listCampaign',
    'shopee_flashsale.listFlashsale',
  ],
});

const store = new Vuex.Store({
  modules,
  plugins: [
    persistStoreLocalStorage,
    persistStoreSessionStorage,
    listenerStore,
  ],
});

export default store;
