import Vue from 'vue';
import { Message } from 'view-design';
import store from '@/vue/store';
import i18n from '@/vue/i18n';
import { hasPlanAccess } from '@/constant/permissions';

const getFeatureName = (to) => {
  if (to.meta.pageTitleKey) {
    return i18n.t(to.meta.pageTitleKey);
  }

  return i18n.t('FEATURE_NAME_DEFAULT');
};

export const guardAuth = (to, from, next) => {
  if (!to.meta.requireAuth) {
    return next();
  }

  if (!store.getters.getIsAuthed) {
    const featureName = getFeatureName(to);
    Vue.nextTick(() => Message.warning(i18n.t('FEATURE_REQUIRE_LOGIN_APP', { name: featureName })));
    return next('/login');
  }

  next();
};

export const guardPlan = (to, from, next) => {
  const requirePlan = to.meta.requirePlan;

  if (!requirePlan) {
    return next();
  }

  if (to.name === 'UpgradePlan') {
    return next();
  }

  if (!hasPlanAccess(store.getters.getUserPlan, requirePlan)) {
    const featureName = getFeatureName(to);
    Vue.nextTick(() => Message.warning(i18n.t('FEATURE_REQUIRE_PAID_PLAN', { name: featureName })));
    return next({
      name: 'UpgradePlan',
      query: {
        redirect: to.fullPath,
        feature: featureName,
        plan: requirePlan,
      },
    });
  }

  next();
};
