import { createRouter, createWebHistory } from 'vue-router'
import { session } from './stores/session'

const router = createRouter({
  history: createWebHistory(),
  routes: [
    { path: '/auth/login', name: 'login', component: () => import('./views/LoginView.vue') },
    { path: '/', redirect: '/todos' },
    {
      path: '/todos',
      name: 'todos',
      component: () => import('./views/TodoView.vue'),
      meta: { requiresAuth: true },
    },
    {
      path: '/team',
      name: 'team',
      component: () => import('./views/TeamView.vue'),
      meta: { requiresAuth: true },
    },
    {
      path: '/settings/user',
      name: 'user-settings',
      component: () => import('./views/UserSettingsView.vue'),
      meta: { requiresAuth: true },
    },
    {
      path: '/settings/team',
      name: 'team-settings',
      component: () => import('./views/TeamSettingsView.vue'),
      meta: { requiresAuth: true },
    },
  ],
})

router.beforeEach((to) => {
  if (to.meta.requiresAuth && !session.token) return '/auth/login'
  if (to.path === '/auth/login' && session.token) return '/todos'
  return true
})

export default router
