import { createRouter, createWebHistory } from 'vue-router'
import LoginView from '../views/LoginView.vue'
import MainMenuView from '../views/MainMenuView.vue'
import createGameView from '../views/CreateGame.vue'
import joinGameView from "@/views/JoinGameView.vue";
import defaultMenu from "../components/DefaultMenu.vue"
import axios from "axios";
import { useUserInfo } from "@/composables/useUserInfo";
import rulesView from "../components/Rules.vue";

const api = window?.__RUNTIME_CONFIG__?.API_URL;

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/mainmenu/',
      component: MainMenuView,
      meta: { requiresAuth: true },
      children: [
        {
          path: '',
          name: 'mainmenu',
          component: defaultMenu,
          meta: { requiresAuth: true }
        },
        {
          path: 'create',
          name: 'create-Game',
          component: createGameView,
          meta: {requiresAuth: true }
        },
        {
          path: 'join',
          name: 'join-Game',
          component: joinGameView,
          meta: {requiresAuth: true }
        },
        {
          path: 'rules',
          name: 'rules-Game',
          component: rulesView,
          meta: {requiresAuth: true }
        },
      ],
    },
    {
      path: '/login',
      name: 'login',
      component: LoginView,
      meta: { requiresAuth: false }
    },
  ],
})

router.beforeEach(async (to, from, next) => {
  const info = useUserInfo();
  if (!to.meta.requiresAuth) return next();
  try {
    await axios.get(`${api}/userInfo`, { withCredentials: true }).then(
      res => {
        info.setUserInfo(res.data.username, res.data.userId);
      }
    );
    next();
  } catch (err) {
    info.clearUserInfo();
    next('/login');
  }
});

export default router



