import { createWebHistory, createRouter } from 'vue-router';
import routes from './routes';
import { useApiStore } from '../stores/api';
import { usePageStore } from '../stores/page';
import { useUserStore } from '../stores/user';

const router = createRouter({
  history: createWebHistory(),
  routes,
});

router.beforeEach(async (to, from, next) => {
  const pageStore = usePageStore();
  const userStore = useUserStore();

  const api = useApiStore();
  try {
    const res = await api.fetchData(to.path);

    if (to.path === '/login' && res.user) {
      location.href = '/';
    }

    pageStore.page = res.page;
    userStore.user = res.user;
    next();
  } catch (error) {
    console.error(error);
    next(false);
  }
});

export { router };
