import { useUserStore } from '@/vue/pinia/user';
import { useUsageStore } from '@/vue/pinia/usage';
import { userSetting, indentifySetting } from '@/plugins/setting';
import { loginUser, getUserInfo, registerUser } from '@/api/autoshopee/user';
import i18n from '@/vue/i18n';
import { cacheDestroyAll } from '@/plugins/store/cache';
import { destroyAllDatabase, pullAllDatabaseRemote } from '@/models/loader';
import { loggerVue } from '@/plugins/logger';

export const actions = {
  SetToken({ commit }, token) {
    commit('SET_USER_TOKEN', token);
  },

  SetUser({ commit }, user) {
    commit('SET_USER_DATA', user);
  },

  SetLogin({ commit }, { username, password }) {
    commit('SET_USER_LOGIN', { username, password });
  },

  UserStore({ state }) {
    const userStore = useUserStore();
    userStore.setUsername(state.username);
    userStore.setUserId(state.id);
    userStore.setUserToken(state.token);
    userStore.setUserData(state.userData);
  },

  async UserLogin({ commit, dispatch }, { username, password }) {
    const profileId = indentifySetting.profileId.get();

    /** @type {UserLogin} */
    const loginResult = await loginUser(username, password, profileId);

    if (loginResult.success && loginResult.token) {
      commit('SET_USER_LOGIN', { username, password });
      commit('SET_USER_TOKEN', loginResult.token);
      commit('SET_USER_DATA', loginResult.data);

      dispatch('UserStore');
      dispatch('UserFetch');
      dispatch('UserSyncRemote');
      useUsageStore().resetUsage();
    }

    return loginResult;
  },

  async UserRegister(_, {
    email, username, password, fullname, phoneNumber, trialRequest,
  }) {
    return registerUser(email, username, password, fullname, phoneNumber, trialRequest);
  },

  async UserFetch({ commit, dispatch }) {
    const userInfo = await getUserInfo();

    if (userInfo.success && userInfo.data && userInfo.data.username) {
      commit('SET_USER_DATA', userInfo.data);
    }

    if (userInfo && userInfo.error && userInfo.error === 403) {
      dispatch('PushMessageError', i18n.t('USER_LOGIN_WAS_LOGOUT'));
      setTimeout(() => {
        dispatch('UserLogout');
      }, 1000);
    }

    return userInfo;
  },

  UseScoreClone({ commit }, platform) {
    commit('DECREASE_USER_SCORE', platform);
  },

  UserLogout({ commit, dispatch, rootState }) {
    commit('SET_USER_LOGOUT');

    userSetting.userExtensionPlan.set('Free');
    userSetting.userId.remove();
    userSetting.userToken.remove();
    userSetting.userData.remove();

    try {
      cacheDestroyAll();
      destroyAllDatabase();

      if (rootState?.lazada?.shop) {
        rootState.lazada.shop.list = [];
        rootState.lazada.shop.selected = '';
      }

      if (rootState?.tiktok?.shop) {
        rootState.tiktok.shop.list = [];
        rootState.tiktok.shop.selected = '';
      }

      if (rootState?.tiktok?.warehouse) {
        rootState.tiktok.warehouse.list = [];
        rootState.tiktok.warehouse.selected = '';
      }

      if (rootState?.shopee_seller?.shopSync) {
        rootState.shopee_seller.shopSync = {};
        rootState.shopee_seller.ref = '';
      }
    } catch (error) {
      loggerVue.error({
        msg: 'SET_USER_LOGUT_ERROR',
        error,
      });
    }

    return dispatch('RouterTo', 'login');
  },

  async UserSyncRemote({ getters }) {
    if (!getters.getIsAuthed) {
      return null;
    }
    return pullAllDatabaseRemote();
  },
};
