import AuthApiService from "../services/AuthApiService";
import Login from "../models/Login";

export default async ({ router, store }) => {
  router.beforeEach((to, from, next) => {
    const idUsuario = store.getters['login/getIdUsuario'];

    if (idUsuario === null && to.path !== '/login') {
      const authApiService = new AuthApiService();
      const token = store.getters['login/getToken']

      if (authApiService.verifyToken(token)) next();

      const loginForm = new Login('admin', '123456');
      authApiService.generateJwt(loginForm).then(resp => {
        store.commit('login/defineToken', resp);
      });

      next('/login');
    }

    next();
  })
}
